package App.Repository;

import App.Job.MyJob;
import App.Model.Account.CrmUser;
import App.Model.BaseEnum;
import App.Model.Chat.CrmChatGroup;
import App.Model.Chat.CrmChatGroupPart;
import App.Model.Friend.CrmUserPart;
import App.Model.PageSummary;
import App.Model.Project.*;
import App.Model.Task.*;
import App.Service.SMSDanMiService;
import App.Service.TecentIMService;
import App.Utility.RandomColorGenerator;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.*;


import org.springframework.transaction.annotation.Transactional;
//import sun.util.resources.cldr.rw.CurrencyNames_rw;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by xw on 2018/11/30.
 */
@Repository
public class TaskRepository extends BaseRepository {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    TecentIMService _imService;

    @Autowired
    CommonRepository _commonRepository;

    @Autowired
    ProjectRepository _projectRepository;

    @Autowired
    SMSDanMiService smsDanMiService;

    //新增
    @Transactional
    public ResultResponse insertTask(TaskSaveRequest _request, String taskid, int userid) throws Exception {

        int result = 0;
        ResultResponse _resultResponse = new ResultResponse();

        try {

            String _taskid = taskid;

            //UUID.randomUUID().toString();
            String _projectid = _request.getProjectid();
            //群组加颜色标记
            String color= RandomColorGenerator.getRandomRGB16();
            int _stageid = _request.getStageid();

            TaskInfo _info = _request.getInfo();
            String _taskName = _info.getTaskname();
            String _taskContent = _info.getContent();
            //Date _begintime = _info.getBegintime();
            int _contenttype = _info.getContenttype();
            String _address = _info.getAddressname();
            String _location = _info.getAddresslocation();
            List<TaskMember> _taskMembers = _request.getMembers();


            if (!_projectid.isEmpty()) {
                // check if the task member include members out of the project stage members.
                List<String> _taskOnlyMember = new ArrayList<>();
                List<CrmProjectMember> _projectMembers = _commonRepository.getProjectStagetMember(_projectid, _stageid, userid);
                for (TaskMember m : _taskMembers) {
                    long _theCount = _projectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                    if (_theCount == 0) {
                        _taskOnlyMember.add(m.getUsername());
                    }
                }

                if (_taskOnlyMember.size() > 0) {
                    String _userNames = StringUtils.join(_taskOnlyMember.toArray(), ",");
                    String _projectName = "";
                    List<CrmProject> _projects = _commonRepository.getProject(_projectid);
                    if (_projects != null && _projects.size() > 0) {
                        _projectName = _projects.get(0).getRecname();
                    }

                    String _stageName = "";
                    List<CrmProjectStage> _projectStages = _commonRepository.getProjectStage(_stageid);
                    if (_projectStages != null && _projectStages.size() > 0) {
                        _stageName = _projectStages.get(0).getStagename();
                    }

                    String _errorMessage = String.format("请先将%s添加到%s项目的%s阶段!", _userNames, _projectName, _stageName);
                    _resultResponse.setMessage(_errorMessage);
                    _resultResponse.setResultcode(-1);
                    return _resultResponse;
                }
            }


            //获取项目的成员
            List<CrmProjectMember> _projectMembers = _commonRepository.getProjectMember(_projectid, userid);

            String _strBeginTime = _info.getBegintime();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date _beginTime = df.parse(_strBeginTime);


            result = insertTaskMain(_taskid, _taskName, _beginTime, _taskContent, _contenttype, _address, _location, userid);

            //添加项目关联数据
            if (_projectid != null && !_projectid.isEmpty() && _stageid > 0) {
                insertTaskProjectRelation(_taskid, _projectid, _stageid, userid);
            }

            //任务联系人
            List<TaskContact> _contacts = _info.getContacts();
            insertTaskContactBatch(_taskid, _contacts, userid);

            //提醒
            List<TaskReminder> _reminders = _request.getReminders();

            //文件
            List<TaskFile> _files = _request.getFiles();
            insertTaskFileBatch(_taskid, _files, userid);

            int _chatType = BaseEnum.ChatType.Task.getChatType();


            //add im group members
            String _lawyerGroupid = UUID.randomUUID().toString();
            boolean _isNotExist = false;
            if (_projectid == null || _projectid.isEmpty()) {
                _isNotExist = true;
            } else {
                for (TaskMember m : _taskMembers) {
                    long _theMemberCount = _projectMembers.stream().filter(x -> x.getStageid() == _stageid && x.getUserid() == m.getUserid()).count();
                    if (_theMemberCount == 0) {
                        _isNotExist = true;
                        break;
                    }
                }
            }

            //如果有项目中不存在的成员，才新建一个聊天组
            if (_isNotExist) {
                //add im group
                //律师协作团队
                int _addGroupResult = 0;

                //String _groupName = _taskName + "律师协作团队";
                String _groupName = "律师协作团队";
                String _imGroupName = "律师协作团队";

                String _taskContentShort = "";
                if (_taskContent.length() > 100) {
                    _taskContentShort = _taskContent.substring(0, 100);
                } else {
                    _taskContentShort = _taskContent;
                }

                //聊天组名称
                if (_taskContent.length() > 10) {
                    _groupName = _taskContent.substring(0, 10);
                } else {
                    _groupName = _taskContent;
                }

                _imGroupName = _groupName;
                String _groupIntroduction = _taskContentShort;


                int _lawyerGroupType = 0;
                _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, _taskid, _stageid, _chatType, _lawyerGroupType, userid,color);
                boolean _createIMGroupResult = false;
                if (_addGroupResult > 0) {
                    _createIMGroupResult = _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userid);
                }
                if (_createIMGroupResult) {
                    System.out.println("create task im group ok ");
                }

                insertTaskMember(_taskid, _lawyerGroupid, _taskMembers, userid);
                if (_createIMGroupResult) {
                    List<Integer> _members = new ArrayList<>();
                    for (TaskMember member : _taskMembers) {
                        _members.add(member.getUserid());
                    }
                    //添加member到im group
                    boolean _addMemberToIM = false;
                    _addMemberToIM = _imService.addIMGroupMember(_lawyerGroupid, _members, userid);
                    if (_addMemberToIM) {
                        System.out.println("add task member to im is ok");
                    }
                }
            } else {
                insertTaskMember(_taskid, "", _taskMembers, userid);
            }


            //保存提醒数据到quartz schedule
            Scheduler _scheduler = StdSchedulerFactory.getDefaultScheduler();
            Calendar cal = Calendar.getInstance();
            for (TaskReminder _r : _reminders) {

                //set begin time for calender
                cal.setTime(_beginTime);

                int _aheadType = _r.getAheadtype();
                //重复方式: 一次，每天，每周
                int _repeattype = _r.getRepeattype();
                //提前分钟数
                int _aheadValue = _r.getAheadvalue();
                //提前时间的类型：时，分，秒，天，
                int _aheadtype = _r.getAheadtype();

                //create cronstring
                TaskScheduleInfo _taskScheduleIfo = createScheduleInfo(_r, cal);
                String _cronString = _taskScheduleIfo.getCronstring();
                Date _scheduleStartDate = _taskScheduleIfo.getBegindatetime();

                //insert reminder
                String _reminderId = UUID.randomUUID().toString();
                insertTaskReminder(_reminderId, _taskid, _repeattype, _aheadValue, _aheadtype, userid);

                //add to database
                String _scheduleId = UUID.randomUUID().toString();
                // insertTaskSchedule(_scheduleId, _taskid, _cronString, _scheduleStartDate, _reminderId, userid);

                //add to quartz
                //insertQuartazSchedule(_scheduler, _taskid, _info, _reminderId, _cronString, _scheduleStartDate);

            }

            //发送群组系统消息
            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            String _userNmae = _theUser.getRealname();

            String _content = "";
            if (_projectid != null && !_projectid.isEmpty() && _stageid > 0) {
                String names = _taskMembers.stream().map(TaskMember::getUsername).collect(Collectors.joining(","));
                _content = String.format("%s创建了任务：%s，开始时间为：%s，任务成员：%s", _userNmae, _taskContent, df.format(_beginTime), names);
            } else {
                _content = String.format("%s创建了本任务，开始时间为：%s", _userNmae, df.format(_beginTime));
            }
            sendIMGroupMessageForTask(_taskid, _content, _taskMembers, userid, 0);
            // 2022/4/28 发送通知消息
            //获取所有成员的手机
            List<Integer> userIdList = _taskMembers.stream().filter(m -> m.getUserid() != userid).map(TaskMember::getUserid).collect(Collectors.toList());
            if (!userIdList.isEmpty()) {
                List<String> phoneList = getPhoneByIds(userIdList);
                logger.info("新建任务发送的手机:" + phoneList);
                smsDanMiService.createTask(phoneList);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }

        _resultResponse.setMessage("");
        _resultResponse.setResultcode(result);

        return _resultResponse;
    }

    //更新
    @Transactional
    public int updateTask(TaskSaveRequest _request, int userid) throws Exception {
        int result = 0;
        try {
            String _taskid = _request.getTaskid();
            TaskInfo _info = _request.getInfo();
            String _taskName = _info.getTaskname();
            String _taskContent = _info.getContent();
            // Date _begintime = _info.getBegintime();
            int _contenttype = _info.getContenttype();
            String _address = _info.getAddressname();
            String _location = _info.getAddresslocation();

            String _projectid = _request.getProjectid();
            //群组加颜色标记
            String color= RandomColorGenerator.getRandomRGB16();
            int _stageidRequst = _request.getStageid();

            //old contacts of info
            List<CrmTaskContact> _savedContacts = getTaskContacts(_taskid);

            //old task members
            List<CrmTaskMember> _savedTaskMembers = getTaskMembers(_taskid);

            //获取关联项目数据
            List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(_taskid);
            if (_relations != null && _relations.size() > 0) {

                CrmTaskProjectRelation _currentRelation = _relations.get(0);
                String _recid = _currentRelation.getRecid();
                String _savedProjectid = _currentRelation.getProjectid();
                int _savedStageid = _currentRelation.getStageid();

                if (_projectid != null) {
                    if (!_projectid.equals(_savedProjectid) || _savedStageid != _stageidRequst) {
                        updateTaskProjectRelation(_recid, _projectid, _stageidRequst);
                    }
                }
            }

            String _strBeginTime = _info.getBegintime();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date _beginTime = df.parse(_strBeginTime);

            //更新任务主数据
            result = updateTaskMain(_taskid, _taskName, _beginTime, _taskContent, _contenttype, _address, _location, userid);

            //====任务联系人
            List<TaskContact> _contacts = _info.getContacts();
            //更新老的联系人
            List<TaskContact> _oldContacts = _contacts.stream().filter(x -> x.getRecid() != null && !x.getRecid().equals("")).collect(Collectors.toList());
            updateTaskContactBatch(_oldContacts, userid);

            //删除老的联系人
            for (CrmTaskContact _c : _savedContacts) {
                List<TaskContact> _tmp = _oldContacts.stream().filter(x -> x.getRecid().equals(_c.getRecid())).collect(Collectors.toList());
                if (_tmp == null || _tmp.size() == 0) {
                    deleteTaskContact(_c.getRecid(), userid);
                }
            }

            //添加新增的联系人
            List<TaskContact> _newContacts = _contacts.stream().filter(x -> x.getRecid() == null || x.getRecid().equals("")).collect(Collectors.toList());
            insertTaskContactBatch(_taskid, _newContacts, userid);

            //=======提醒
            Scheduler _scheduler = StdSchedulerFactory.getDefaultScheduler();
            List<TaskReminder> _reminders = _request.getReminders();
            List<CrmTaskSchedule> _oldSchedules = getTaskSchedulesByTaskId(_taskid);
            List<CrmTaskReminder> _savedTaskReminders = getTaskReminders(_taskid);

            List<CrmTask> _savedTasks = getTaskInfo(_taskid);
            CrmTask _currentTask = _savedTasks.get(0);

            Calendar cal = Calendar.getInstance();

            //更新提醒
            List<TaskReminder> _oldReminders = _reminders.stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
            Date _oldTaskBeginTime = _currentTask.getBegintime();

            //delete old task
            for (CrmTaskReminder _r : _savedTaskReminders) {
                deleteTaskReminder(_r.getRecid(), userid);
            }

            for (TaskReminder r : _reminders) {
                // insert reminder
                String _reminderId = UUID.randomUUID().toString();
                //insert reminder data
                int _repeatType = r.getRepeattype();
                int _aheadValue = r.getAheadvalue();
                int _aheadType = r.getAheadtype();
                insertTaskReminder(_reminderId, _taskid, _repeatType, _aheadValue, _aheadType, userid);
            }


            //=======文件
            List<TaskFile> _files = _request.getFiles();

            //删除文件
            List<TaskFile> _oldfiles = _files.stream().filter(x -> x.getRecid() != null && !x.getRecid().equals("")).collect(Collectors.toList());
            List<CrmTaskFile> _savedfiles = getTaskFiles(_taskid);
            for (CrmTaskFile _f : _savedfiles) {
                List<TaskFile> _tmp = _oldfiles.stream().filter(x -> x.getRecid().equals(_f.getRecid())).collect(Collectors.toList());
                if (_tmp == null || _tmp.size() == 0) {
                    deleteTaskFile(_f.getRecid(), userid);
                }
            }

            //新增文件
            List<TaskFile> _newfiles = _files.stream().filter(x -> x.getRecid().equals("")).collect(Collectors.toList());
            insertTaskFileBatch(_taskid, _newfiles, userid);


            //获取项目的成员
            List<CrmProjectMember> _projectMembers = _commonRepository.getProjectMember(_projectid, userid);
            List<TaskMember> _taskMembers = _request.getMembers();
            boolean _isNotExist = false;
            if (_projectid == null || _projectid.isEmpty()) {
                _isNotExist = true;
            } else {
                for (TaskMember m : _taskMembers) {
                    long _theMemberCount = _projectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                    if (_theMemberCount == 0) {
                        _isNotExist = true;
                        break;
                    }
                }
            }

            String _lawyerGroupid = "";
            List<CrmChatGroupPart> _theTaskChatGroups = _commonRepository.getTaskChatGroup(_taskid);
            if (_theTaskChatGroups != null && _theTaskChatGroups.size() > 0) {
                _lawyerGroupid = _theTaskChatGroups.get(0).getGroupid();
            }

            //团队成员
            int _chatType = BaseEnum.ChatType.Task.getChatType();

            //is exists member not in project member, create new chat group
            if (_isNotExist) {
                if (_lawyerGroupid.isEmpty()) {
                    int _addGroupResult = 0;
                    _lawyerGroupid = UUID.randomUUID().toString();
                    // String _groupName = _taskName + "_律师协作团队";
                    String _groupName = "律师协作团队";
                    String _imGroupName = "律师协作团队";


                    String _taskContentShort = "";
                    if (_taskContent.length() > 100) {
                        _taskContentShort = _taskContent.substring(0, 100);
                    }
                    String _groupIntroduction = _taskContentShort;

                    int _lawyerGroupType = 0;
                    int _stageid = 0;
                    _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, _taskid, _stageid, _chatType, _lawyerGroupType, userid,color);
                    boolean _createIMGroupResult = false;
                    if (_addGroupResult > 0) {
                        _createIMGroupResult = _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userid);

                    }
                    if (_createIMGroupResult) {
                        System.out.println("create task im group ok ");
                    }
                } else {
                    //更新chat_group data recstatus=1
                    _commonRepository.updateChatGroupStatus(_lawyerGroupid, 1);
                }
            }

            // if bind to project, and all task member belong project member,disable task chat group
            if (!_isNotExist) {
                if (!_lawyerGroupid.isEmpty()) {
                    //更新chat_group data recstatus=0
                    _commonRepository.updateChatGroupStatus(_lawyerGroupid, 0);
                }
            }


            //删除老成员
            List<TaskMember> _oldMembers = _taskMembers.stream().filter(x -> x.getRecid() != null && !x.getRecid().isEmpty()).collect(Collectors.toList());
            for (CrmTaskMember _m : _savedTaskMembers) {
                String _mRecid = _m.getRecid();
                List<TaskMember> _tmp = _oldMembers.stream().filter(x -> x.getRecid().equals(_mRecid)).collect(Collectors.toList());
                if (_tmp == null || _tmp.size() == 0) {
                    deleteTaskMember(_m.getRecid(), userid);
                }
            }

            //添加新成员
            List<TaskMember> _newMembers = _taskMembers.stream().filter(x -> x.getRecid() == null || x.getRecid().equals("")).collect(Collectors.toList());
            if (_newMembers != null && _newMembers.size() > 0) {
                insertTaskMember(_taskid, _lawyerGroupid, _newMembers, userid);
            }

            //更新老成员
            updateTaskMember(_oldMembers, userid);


            //发送信息变更聊天群系统消息`
            try {

                //get chat group id
                String _theTaskChatGroupId = "";
                String _theProjectClientChatGroupId = "";
                String _theProjectLawyerChatGroupId = "";
                List<String> _chatGroupIds = new ArrayList<>();

                List<CrmChatGroupPart> _taskChatGroup = _commonRepository.getTaskChatGroup(_taskid);
                if (_taskChatGroup != null && _taskChatGroup.size() > 0) {
                    _theTaskChatGroupId = _taskChatGroup.get(0).getGroupid();
                }

                if (_projectid.isEmpty()) {
                    _chatGroupIds.add(_theTaskChatGroupId);
                } else {
                    if (_theTaskChatGroupId.isEmpty()) {
                        if (_taskMembers != null && _taskMembers.size() > 0) {
                            boolean _isInClientMember = false;
                            boolean _isInLawyerMember = false;
                            List<CrmChatGroupPart> _projectChatGroup = _commonRepository.getProjectChatGroup(_projectid);
                            List<CrmChatGroupPart> _projectStageChatGroup = _projectChatGroup.stream().filter(x -> x.getStageid() == _request.getStageid()).collect(Collectors.toList());
                            Optional<CrmChatGroupPart> _projectClientChatGroup = _projectStageChatGroup.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();
                            Optional<CrmChatGroupPart> _projectLawyerChatGroup = _projectStageChatGroup.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();
                            if (_projectClientChatGroup.isPresent()) {
                                _theProjectClientChatGroupId = _projectClientChatGroup.get().getGroupid();
                            }
                            if (_projectLawyerChatGroup.isPresent()) {
                                _theProjectLawyerChatGroupId = _projectLawyerChatGroup.get().getGroupid();
                            }


                            //if task member in project client member, lawyer member
                            List<CrmProjectMember> _theProjectMembers = _commonRepository.getProjectMember(_projectid, userid);
                            for (TaskMember m : _taskMembers) {
                                List<CrmProjectMember> _tempMembers = _theProjectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).collect(Collectors.toList());
                                long _theClientCount = _tempMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).count();
                                if (_theClientCount > 0) {
                                    _isInClientMember = true;
                                } else {
                                    long _theLawyerCount = _tempMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()).count();
                                    if (_theLawyerCount > 0) {
                                        _isInLawyerMember = true;
                                    }
                                }
                            }
                            if (_isInClientMember) {
                                _chatGroupIds.add(_theProjectClientChatGroupId);
                            }

                            if (_isInLawyerMember) {
                                _chatGroupIds.add(_theProjectLawyerChatGroupId);
                            }
                        }

                    } else {
                        _chatGroupIds.add(_theTaskChatGroupId);
                    }
                }


                List<String> _messageContents = new ArrayList<>();


                //maanager, host change
                Optional<CrmTaskMember> _theHostMember = _savedTaskMembers.stream().filter(x -> x.ishost()).findFirst();
                Optional<CrmTaskMember> _theManagerMember = _savedTaskMembers.stream().filter(x -> x.ismanager()).findFirst();

                Optional<TaskMember> _theRequestHostMember = _taskMembers.stream().filter(x -> x.getIshost()).findFirst();
                Optional<TaskMember> _theRequestManagerMember = _taskMembers.stream().filter(x -> x.getIsmanager()).findFirst();


                //check if host change
                if (_theRequestHostMember.isPresent() && _theHostMember.isPresent()) {
                    if (_theRequestHostMember.get().getUserid() != _theHostMember.get().getUserid()) {
                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestHostMember.get().getUserid());
                        String _theContent = String.format("主办人变更为%s", _theUser.getRealname());
                        _messageContents.add(_theContent);
                    }
                }

                //check if manager change
                if (_theRequestManagerMember.isPresent() != _theManagerMember.isPresent()) {
                    if (_theRequestManagerMember.get().getUserid() != _theManagerMember.get().getUserid()) {
                        CrmUser _theUser = _commonRepository.getUserInfo(_theRequestManagerMember.get().getUserid());
                        String _theContent = String.format("管理员变更为%s", _theUser.getRealname());
                        _messageContents.add(_theContent);
                    }
                }

                boolean _isInfoChanged = false;
                boolean _isReminderChanged = false;
                boolean _isFileChanged = false;
                boolean _isMemberChanged = false;

                //检查信息是否发生了改变
                //关联项目


                if (!_isInfoChanged) {
                    if (_relations != null && _relations.size() > 0) {
                        int _theStageid = _relations.get(0).getStageid();
                        String _theProjectid = _relations.get(0).getProjectid();
                        if (!_theProjectid.equals(_projectid) || _theStageid != _request.getStageid()) {
                            _isInfoChanged = true;
                        }
                    } else {

                        if (!_projectid.isEmpty() && _request.getStageid() > 0) {
                            _isInfoChanged = true;
                        }
                    }
                }

                if (!_isInfoChanged) {
                    if (!_currentTask.getContent().equals(_info.getContent())) {
                        _isInfoChanged = true;
                    }
                }

                if (!_isInfoChanged) {
                    SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String _savedBeginTime = _dataFormat.format(_currentTask.getBegintime());
                    if (!_savedBeginTime.equals(_info.getBegintime())) {
                        _isInfoChanged = true;
                    }
                }

                //任务地点
                if (!_isInfoChanged) {

                    if (_currentTask != null) {
                        if (_currentTask.getAddressname() != null && _info.getAddressname() != null) {
                            if (!_currentTask.getAddressname().equals(_info.getAddressname())) {
                                _isInfoChanged = true;
                            } else {
                                if ((_currentTask.getAddressname() == null || _currentTask.getAddressname().isEmpty()) && (_info.getAddressname() != null && !_info.getAddressname().isEmpty())) {
                                    _isInfoChanged = true;
                                }

                                if ((_currentTask.getAddressname() != null && !_currentTask.getAddressname().isEmpty()) && (_info.getAddressname() == null || _info.getAddressname().isEmpty())) {
                                    _isInfoChanged = true;
                                }
                            }
                        }
                    }
                }

                //联系人
                if (!_isInfoChanged) {
                    if (_info.getContacts() != null && _info.getContacts().size() > 0) {
                        if (_savedContacts != null) {
                            if (_info.getContacts().size() != _savedContacts.size()) {
                                _isInfoChanged = true;
                            }
                            for (TaskContact c : _info.getContacts()) {
                                long _theContactCount = _savedContacts.stream().filter(x -> x.getName().equals(c.getName())
                                        && x.getPhone().equals(c.getPhone())).count();
                                if (_theContactCount == 0) {
                                    _isInfoChanged = true;
                                    break;
                                }
                            }
                        } else {
                            _isInfoChanged = true;
                        }
                    } else {
                        if (_savedContacts != null && _savedContacts.size() > 0) {
                            _isInfoChanged = true;
                        }
                    }

                    if (!_isInfoChanged) {

                        if (_savedContacts != null && _savedContacts.size() > 0) {
                            for (CrmTaskContact c : _savedContacts) {
                                long _theContactCount = _info.getContacts().stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                                if (_theContactCount == 0) {
                                    _isInfoChanged = true;
                                }
                            }
                        } else {

                            if (_info.getContacts() != null && _info.getContacts().size() > 0) {
                                _isInfoChanged = true;
                            }
                        }
                    }
                }

                //提醒
                if (_reminders != null && _reminders.size() > 0) {
                    if (_savedTaskReminders != null && _savedTaskReminders.size() > 0) {
                        long _theReminderCount = _reminders.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).count();
                        if (_theReminderCount > 0) {
                            _isReminderChanged = true;
                        } else {
                            for (CrmTaskReminder r : _savedTaskReminders) {
                                long _theCount = _reminders.stream().filter(x -> x.getRepeattype() == r.getRepeattype()
                                        && x.getAheadtype() == r.getAheadtype() && x.getAheadvalue() == r.getMinutes()).count();

                                if (_theCount == 0) {
                                    _isReminderChanged = true;
                                }
                            }
                        }
                    } else {
                        _isReminderChanged = true;
                    }
                } else {
                    if (_savedTaskReminders != null && _savedTaskReminders.size() > 0) {
                        _isReminderChanged = true;
                    }
                }

                // 资料
                if (_files != null && _files.size() > 0) {

                    if (_savedfiles == null || _savedfiles.size() == 0) {
                        _isFileChanged = true;
                    } else {
                        long _theFileCount = _files.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).count();
                        if (_theFileCount > 0) {
                            _isFileChanged = true;
                        }
                    }
                } else {
                    if (_savedfiles != null & _savedfiles.size() > 0) {
                        _isFileChanged = true;
                    }
                }

                if (_savedfiles != null && _savedfiles.size() > 0) {
                    if (_files == null && _files.size() == 0) {
                        _isFileChanged = true;
                    } else {
                        for (CrmTaskFile f : _savedfiles) {
                            long _theFileCount = _files.stream().filter(x -> x.getRecid().equals(f.getRecid())).count();
                            if (_theFileCount == 0) {
                                _isFileChanged = true;
                                break;
                            }
                        }
                    }
                }


                //成员
                //原来没有成员
                if (_taskMembers != null && _taskMembers.size() > 0) {
                    if (_savedTaskMembers == null || _savedTaskMembers.size() == 0) {
                        _isMemberChanged = true;
                    }
                }

                //把所有成员删除了
                if (_savedTaskMembers != null && _savedTaskMembers.size() > 0) {
                    if (_taskMembers == null || _taskMembers.size() == 0) {
                        _isMemberChanged = true;
                    }
                }


                if (_taskMembers != null && _taskMembers.size() > 0) {
                    long _theRequestNewMemberCount = _taskMembers.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).count();
                    if (_theRequestNewMemberCount > 0) {
                        _isMemberChanged = true;
                    }
                    if (_savedTaskMembers != null && _savedTaskMembers.size() > 0) {
                        for (TaskMember m : _taskMembers) {
                            long _theTaskMemberCount = _savedTaskMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                            if (_theTaskMemberCount == 0) {
                                _isMemberChanged = true;
                                break;
                            }
                        }
                    } else {
                        _isMemberChanged = true;
                    }
                } else {
                    if (_savedTaskMembers != null && _savedTaskMembers.size() > 0) {
                        _isMemberChanged = true;
                    }
                }

                if (!_isMemberChanged) {
                    if (_savedTaskMembers != null && _savedTaskMembers.size() > 0) {
                        if (_taskMembers != null && _taskMembers.size() > 0) {
                            for (CrmTaskMember m : _savedTaskMembers) {
                                long _theTaskMemberCount = _taskMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                                if (_theTaskMemberCount == 0) {
                                    _isMemberChanged = true;
                                    break;
                                }
                            }
                        } else {
                            _isMemberChanged = true;
                        }
                    } else {
                        if (_taskMembers != null && _taskMembers.size() > 0) {
                            _isMemberChanged = true;
                        }
                    }
                }

                String _theTaskContent = _currentTask.getContent();
                //send message
                if (_isInfoChanged) {
                    CrmUser _theUser = _commonRepository.getUserInfo(userid);
                    String _theContent = String.format("%s编辑了任务%s的信息", _theUser.getRealname(), _theTaskContent);
                    _messageContents.add(_theContent);
                }
                if (_isReminderChanged) {
                    CrmUser _theUser = _commonRepository.getUserInfo(userid);
                    String _theContent = String.format("%s编辑了任务%s的提醒", _theUser.getRealname(), _theTaskContent);
                    _messageContents.add(_theContent);
                }
                if (_isFileChanged) {
                    CrmUser _theUser = _commonRepository.getUserInfo(userid);
                    String _theContent = String.format("%s编辑了任务%s的资料", _theUser.getRealname(), _theTaskContent);
                    _messageContents.add(_theContent);
                }
                if (_isMemberChanged) {
                    CrmUser _theUser = _commonRepository.getUserInfo(userid);
                    String _theContent = String.format("%s编辑了任务%s的成员", _theUser.getRealname(), _theTaskContent);
                    _messageContents.add(_theContent);
                }

                //send real message
                for (String _message : _messageContents) {
                    sendIMMessage(_taskid, _chatGroupIds, _message, userid, 0);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                logger.info(ex.getMessage());
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

    //列表
    public List<TaskInfoList> getTaskListResponse(TaskListRequest _request, int userid) {

        List<CrmTask> _tasks = new ArrayList<>();
        List<TaskInfoList> _aheadTypeResponse = new ArrayList<>();
        EntityManager _entityManager = getEntityManager();

        SimpleDateFormat _dataFormat24Hour = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            _tasks = getTaskListMainPage(_request, userid);

            if (_tasks != null && _tasks.size() > 0) {
                for (CrmTask _t : _tasks) {

                    String _taskid = _t.getRecid();
                    TaskInfoList _info = toTaskInfoList(_t);
                    _info.setCompletedtime(_dataFormat24Hour.format(_t.getCompletetime()));


                    List<CrmTaskFile> _taskFiles = getTaskFiles(_taskid);
                    if (_taskFiles != null && _taskFiles.size() > 0) {
                        _info.setHasfile(true);
                    } else {
                        _info.setHasfile(false);
                    }

                    List<CrmTaskMember> _members = getTaskMembers(_taskid);


                    //set project name and stage name
                    List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(_taskid);
                    if (_relations != null && _relations.size() > 0) {

                        String _projectName = "";
                        String _stageName = "";
                        int _projectType = 0;

                        CrmTaskProjectRelation _relation = _relations.stream().findFirst().get();
                        String _projectid = _relation.getProjectid();
                        if (_projectid != null && !_projectid.isEmpty()) {
                            List<CrmProject> _projectList = _commonRepository.getProject(_projectid);
                            if (_projectList != null && _projectList.size() > 0) {
                                CrmProject _project = _projectList.get(0);
                                _projectName = _project.getRecname();
                                _projectType = _project.getProjecttype();

                                List<CrmProjectStage> _stageList = _commonRepository.getProjectStageList(_projectid);
                                if (_stageList != null && _stageList.size() > 0) {
                                    CrmProjectStage _stageInfo = _stageList.get(0);
                                    _stageName = _stageInfo.getStagename();
                                }
                            }
                        }
                        _info.setProjectname(_projectName);
                        _info.setProjectid(_relation.getProjectid());
                        _info.setProjecttype(_projectType);
                        _info.setStagename(_stageName);
                        _info.setStageid(_relation.getStageid());

                        List<CrmProjectMember> _tmpProjectMembers = new ArrayList<>();

                        List<CrmProjectMember> _ProjectMembers = _commonRepository.getProjectMember(_projectid, userid);
                        if (_ProjectMembers != null && _ProjectMembers.size() > 0) {
                            List<CrmProjectMember> _clientProjectMembers = _ProjectMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());
                            List<CrmProjectMember> _lawyertProjectMembers = _ProjectMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()).collect(Collectors.toList());
                            for (CrmProjectMember m : _clientProjectMembers) {
                                long _theCount = _lawyertProjectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                                if (_theCount == 0) {
                                    _tmpProjectMembers.add(m);
                                }
                            }
                            if (_tmpProjectMembers != null && _tmpProjectMembers.size() > 0) {
                                for (CrmProjectMember tm : _tmpProjectMembers) {
                                    long _theTaskCount = _members.stream().filter(x -> x.getUserid() == tm.getUserid()).count();
                                    if (_theTaskCount > 0) {
                                        _info.setIsclientvisible(true);
                                    }
                                }
                            } else {
                                _info.setIsclientvisible(false);
                            }
                        } else {
                            _info.setIsclientvisible(false);
                        }
                    } else {
                        _info.setProjectname("");
                        _info.setStagename("");
                        _info.setIsclientvisible(false);
                    }


                    List<CrmTaskMember> _tmpMembers1 = _members.stream().filter(x -> x.getUserid() == userid && x.ishost()).collect(Collectors.toList());
                    boolean _isHost = false;
                    if (_tmpMembers1 != null && _tmpMembers1.size() > 0) {
                        _isHost = true;
                    }

                    boolean _isManager = false;
                    List<CrmTaskMember> _tmpMembers2 = _members.stream().filter(x -> x.getUserid() == userid && x.ismanager()).collect(Collectors.toList());
                    if (_tmpMembers2 != null && _tmpMembers2.size() > 0) {
                        _isManager = true;
                    }
                    _info.setIshost(_isHost);
                    _info.setIsmanager(_isManager);

                    CrmChatGroup _chatGroup = _commonRepository.getChatGroup(_taskid);
                    if (_chatGroup != null) {
                        String _groupid = _chatGroup.getGroupid();
                        _info.setChatgroupid(_groupid);
                    } else {
                        _info.setChatgroupid("");
                    }
                    _aheadTypeResponse.add(_info);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
        }
        return _aheadTypeResponse;
    }

    //详情
    public TaskGetDetailResponse getTaskDetail(TaskGetDetailRequest _request, int userid) {

        TaskGetDetailResponse _response = new TaskGetDetailResponse();
        String _taskid = _request.getTaskid();

        EntityManager _entityManager = getEntityManager();

        int result = 0;
        try {
            //set info
            List<CrmTask> _taskList = getTaskInfo(_taskid);
            CrmTask _currentTask = _taskList.get(0);
            TaskInfo _info = toTaskInfo(_currentTask);

            if (_info.getTaskname() == null) {
                _info.setTaskname("");
            }

            //chat group
            TaskChatGroup _theChatGroup = new TaskChatGroup();
            List<CrmChatGroupPart> _chatGroup = _commonRepository.getTaskChatGroup(_taskid);
            if (_chatGroup != null && _chatGroup.size() > 0) {
                _info.setChatgroupid(_chatGroup.get(0).getGroupid());
            } else {
                _info.setChatgroupid("");
            }

            String _projectid = "";
            int _stageid = 0;
            List<CrmTaskProjectRelation> _projectTasks = getTaskProjectRelation(_taskid);
            if (_projectTasks != null && _projectTasks.size() > 0) {
                CrmTaskProjectRelation _relation = _projectTasks.get(0);
                _projectid = _relation.getProjectid();
                _stageid = _relation.getStageid();
                _info.setProjectid(_projectid);
                _info.setStageid(_stageid);

                List<CrmProject> _projectList = _commonRepository.getProject(_entityManager, _projectid);
                if (_projectList != null && _projectList.size() > 0) {
                    CrmProject _project = _projectList.stream().findFirst().get();
                    String _projectName = _project.getRecname();
                    _info.setProjectname(_projectName);
                    _info.setProjecttype(_project.getProjecttype());
                }

                List<CrmProjectStageName> _stages = getProjectStageName(_stageid);
                if (_stages != null && _stages.size() > 0) {
                    CrmProjectStageName _stageName = _stages.get(0);
                    _info.setStagename(_stageName.getStagename());
                }
            }

            //set contact
            List<CrmTaskContact> _contacts = getTaskContacts(_taskid);
            List<TaskContact> _contactsResponse = new ArrayList<>();
            for (CrmTaskContact _c : _contacts) {
                _contactsResponse.add(toTaskContact(_c));
            }
            _info.setContacts(_contactsResponse);
            _response.setInfo(_info);

            //set reminder
            List<CrmTaskReminder> _reminders = getTaskReminders(_taskid);
            List<TaskReminder> _remindersResponse = new ArrayList<>();
            for (CrmTaskReminder _r : _reminders) {
                _remindersResponse.add(toTaskReminder(_r));
            }
            _response.setReminders(_remindersResponse);

            //set files
            List<CrmTaskFile> _files = getTaskFiles(_taskid, userid);
            List<TaskFile> _filesResponse = new ArrayList<>();
            for (CrmTaskFile _f : _files) {
                _filesResponse.add(toTaskFile(_f));
            }
            _response.setFiles(_filesResponse);

            //set members
            List<CrmTaskMember> _members = getTaskMembers(_taskid);
            List<TaskMember> _membersResponse = new ArrayList<>();
            for (CrmTaskMember _m : _members) {

                TaskMember _theMember = toCrmTaskMember(_m);
                CrmUserPart _theUserInfo = _commonRepository.getUserInfoALL(_m.getUserid());
                if (_theMember != null) {
                    String _theHeadImage = _theUserInfo.getHeadimage();
                    _theMember.setHeadimage(_theHeadImage);
                } else {
                    _theMember.setHeadimage("");
                }
                _membersResponse.add(_theMember);
            }

            for (CrmTaskMember _m : _members) {
                if (_m.getUserid() == userid) {
                    if (_m.ishost()) {
                        _info.setIshost(true);
                    }
                    if (_m.ismanager()) {
                        _info.setIsmanager(true);
                    }
                }
            }
            _response.setMembers(_membersResponse);


        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
        }
        return _response;
    }

    //获取提醒提前类型
    public List<TaskAheadType> getAheadTypeResponse() {

        List<CrmTaskAheadType> _aheadTypes = new ArrayList<>();
        try {
            _aheadTypes = getTaskAheadType();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }

        List<TaskAheadType> _aheadTypeResponse = new ArrayList<>();
        if (_aheadTypes != null && _aheadTypes.size() > 0) {
            for (CrmTaskAheadType _t : _aheadTypes) {
                _aheadTypeResponse.add(toCrmTaskAheadType(_t));
            }
        }
        return _aheadTypeResponse;
    }

    //获取提醒重复类型
    public List<TaskRepeatType> getTaskRepeatTypeResponse() {
        List<CrmTaskRepeatType> _aheadTypes = new ArrayList<>();
        try {
            _aheadTypes = getTaskRepeatType();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        List<TaskRepeatType> _aheadTypeResponse = new ArrayList<>();
        if (_aheadTypes != null && _aheadTypes.size() > 0) {
            for (CrmTaskRepeatType _t : _aheadTypes) {
                _aheadTypeResponse.add(toTaskRepeatType(_t));
            }
        }
        return _aheadTypeResponse;
    }

    //删除任务
    @Transactional
    public int deleteTask(TaskDeleteRequest _request, int userid) {

        int result = 0;
        String taskid = _request.getTaskid();
        List<CrmTask> _taskInfos = getTaskInfo(taskid);
        String _taskContent = "";
        if (_taskInfos != null && _taskInfos.size() > 0) {
            _taskContent = _taskInfos.get(0).getContent();
        }


        CrmUser _theUser = _commonRepository.getUserInfo(userid);
        String _userNmae = _theUser.getRealname();
        String _content = String.format("%s删除了任务%s", _userNmae, _taskContent);
        sendIMGroupMessageForTask(taskid, _content, null, userid, 0);


        List<CrmTaskProjectRelation> _relates = getTaskProjectRelation(taskid);
        if (_relates != null && _relates.size() > 0) {
            String _relateId = _relates.get(0).getRecid();
            deleteTaskProjectRelation(_relateId);

            //发送系统消息给project
            String _projectId = _relates.get(0).getProjectid();
            int _stageId = _relates.get(0).getStageid();
            if (_projectId != null && !_projectId.isEmpty()) {
                List<CrmChatGroupPart> _chatGroups = _commonRepository.getProjectChatGroup(_projectId);
                if (_chatGroups != null && _chatGroups.size() > 0) {

                    List<CrmChatGroupPart> _theChatGroups = _chatGroups.stream().filter(x -> x.getStageid() == _stageId).collect(Collectors.toList());
                    List<String> _theGroupIds = new ArrayList<>();
                    for (CrmChatGroupPart c : _theChatGroups) {
                        _theGroupIds.add(c.getGroupid());
                    }

                   /* CrmUser _theUser = _commonRepository.getUserInfo(userid);
                    String _userNmae = _theUser.getRealname();
                    String _content = String.format("%s删除了任务%s", _userNmae, _taskContent);
                   sendIMMessage(_theGroupIds, _content, userid);*/

                }
            }
        }
        result = deleteTask(taskid, userid);
        if (result > 0) {

            //delete chat group

         /*   CrmUser _theUser = _commonRepository.getUserInfo(userid);
            String _userNmae = _theUser.getRealname();
            String _content = String.format("%s删除了任务%s", _userNmae, _taskContent);
            sendIMGroupMessageForTask(taskid, _content, null, userid);
            */
        }

        return result;
    }

    //完成任务
    @Transactional
    public int completeTaskSimple(TaskCompleteRequest _request, int userid) throws Exception {
        int result = 0;
        try {
            String taskid = _request.getTaskid();
            result = completeTask(taskid, userid);
            if (result > 0) {
                CrmChatGroup _theTaskChatGroup = getTaskChatGroup(taskid);
                if (_theTaskChatGroup != null) {
                    String _theTaskChatGroupId = _theTaskChatGroup.getGroupid();
                    setTaskChatGroupActive(_theTaskChatGroupId, false);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

    //暂停任务
    @Transactional
    public int pauseTask(TaskPauseRequest _request, int userid) {
        int result = 0;
        try {
            String taskid = _request.getTaskid();
            result = pauseTask(taskid, userid);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

    //重启任务
    @Transactional
    public int restartTaskSimple(TaskRestartRequest _request, int userid) throws Exception {
        int result = 0;
        try {
            String taskid = _request.getTaskid();
            result = restartTask(taskid, userid);
            //TODO 这里是否需要注销腾讯IM群聊
            if (result > 0) {
                CrmChatGroup _theTaskChatGroup = getTaskChatGroup(taskid);
                if (_theTaskChatGroup != null) {
                    String _theTaskChatGroupId = _theTaskChatGroup.getGroupid();
                    setTaskChatGroupActive(_theTaskChatGroupId, true);
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

    //转移管理员角色
    @Transactional
    public int transferManager(TaskTransferManagerRequest _request, int userid) {
        int _result = 0;
        try {
            String taskid = _request.getTaskid();
            String _fromMemberid = _request.getFrommemberid();
            String _toMemberid = _request.getTomemberid();
            _result = transferManager(_fromMemberid, false, userid);
            _result = transferManager(_toMemberid, true, userid);

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    //转移主办人角色
    @Transactional
    public int transferHost(TaskTransferHostRequest _request, int userid) {

        int _result = 0;
        try {

            String taskid = _request.getTaskid();
            String _fromMemberid = _request.getFrommemberid();
            String _toMemberid = _request.getTomemberid();

            _result = transferHost(_fromMemberid, false, userid);
            _result = transferHost(_toMemberid, true, userid);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    //获取schedule列表
    public List<CrmTaskSchedule> getTaskSchedules() {
        List<CrmTaskSchedule> _schedules = new ArrayList<>();
        try {
            _schedules = getTaskSchedulesBase();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _schedules;
    }

    //合并任务文件到项目文件夹
    @Transactional
    public int taskFileMerge(TaskFileMergeRequest _request, int userid) {
        int _result = 0;
        int _finalResult = 0;

        try {
            String _projectid = _request.getProjectid();
            int _stageid = _request.getStageid();
            String _folderid = _request.getFolderid();
            List<TaskFile> _files = _request.getFiles();

            for (TaskFile f : _files) {
                String _recid = UUID.randomUUID().toString();
                ProjectFile _file = new ProjectFile();
                _file.setFolderid(_folderid);
                _file.setUploadfileid(f.getUploadfileid());
                _file.setFilename(f.getFilename());
                _result = _commonRepository.insertProjectFile(getEntityManager(), _projectid, _stageid, _recid, _file, userid);
                _finalResult += _result;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
        }
        return _finalResult;
    }

    // 写入上传文件记录
    @Transactional
    public int insertFileUploadRecord(String fileid, String oldFileName, String newFileName, String
            showFileName, String fileSuffix, int userid) {
        int _result = 0;
        try {

            String _strSql =
                    " insert into crm_upload_file(recid,fileid,oldfilename,newfilename,showfilename,filesuffix,reccreator) " +
                            " values(:recid,:fileid,:oldfilename,:newfilename,:showfilename,:filesuffix,:reccreator) ";

            String _recid = UUID.randomUUID().toString();
            javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
            _query.setParameter("recid", _recid);
            _query.setParameter("fileid", fileid);
            _query.setParameter("oldfilename", oldFileName);
            _query.setParameter("newfilename", newFileName);
            _query.setParameter("showfilename", showFileName);
            _query.setParameter("filesuffix", fileSuffix);
            _query.setParameter("reccreator", userid);
            _result = _query.executeUpdate();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    //获取接收提醒的人
    public TaskJobInfo getReminderMember(String reminderid) {
        TaskJobInfo _jobInfo = new TaskJobInfo();
        List<Integer> _ids = new ArrayList<>();
        int _result = 0;
        try {
            String _taskid = "";
            List<CrmTaskReminder> _reminders = getReminders(reminderid);
            if (_reminders != null && _reminders.size() > 0) {
                CrmTaskReminder _reminder = _reminders.get(0);
                _taskid = _reminder.getTaskid();

                String _strSql = " select m.userid from crm_task_member m " +
                        "  where m.taskid=:taskid  " +
                        " and m.userid not in (select reccreator from crm_task_reminder where taskid=:taskid )" +
                        " and m.userid>0 " +
                        " and m.recstatus=1 " +
                        " union (select reccreator from  crm_task_reminder where recid=:reminderid ) ";

                javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, Integer.class);
                _query.setParameter("taskid", _taskid);
                _query.setParameter("reminderid", reminderid);
                _ids = _query.getResultList();
            }

            _jobInfo.setMembers(_ids);

            //设置任务
            List<CrmTask> _tasks = getTaskInfo(_taskid);
            if (_tasks != null && _tasks.size() > 0) {
                CrmTask _task = _tasks.get(0);
                _jobInfo.setTaskbegintime(_task.getBegintime().toString());
                _task.setContent(_task.getContent());
            }

            if (!_taskid.isEmpty()) {

                //设置项目
                List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(_taskid);
                CrmTaskProjectRelation _relation = _relations.get(0);
                String _projectid = _relation.getProjectid();
                int _stageid = _relation.getStageid();
                List<CrmProject> _projects = _commonRepository.getProject(getEntityManager(), _projectid);
                if (_projects != null && _projects.size() > 0) {
                    CrmProject _project = _projects.get(0);
                    _jobInfo.setProjectname(_project.getRecname());
                    _jobInfo.setProjectid(_projectid);
                }

                //设置阶段
                List<CrmProjectStageName> _stages = getProjectStageName(_stageid);
                if (_stages != null && _stages.size() > 0) {
                    CrmProjectStageName _stage = _stages.get(0);
                    _jobInfo.setStagename(_stage.getStagename());
                    _jobInfo.setStageid(_stageid);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _jobInfo;
    }


    /* inner method */

    //task
    public List<CrmTask> getTaskList(String searchKey, int userid) {

        String _strSql = " select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime" +
                " from crm_task " +
                " where recstatus=1 " +
                " and  recid in (select taskid   from crm_task_member where recstatus=1 and userid=:userid)" +
                " and  content like  '%" + searchKey + "%'" +
                " order by createtime desc ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTask.class);
        _query.setParameter("userid", userid);
        return _query.getResultList();
    }


    public TaskMember toCrmTaskMember(CrmTaskMember member) {
        TaskMember _member = new TaskMember();
        _member.setRecid(member.getRecid());
        _member.setUserid(member.getUserid());
        _member.setUsername(member.getUsername());
        _member.setIshost(member.ishost());
        _member.setIsmanager(member.ismanager());
        _member.setCreator(member.getReccreator());
        _member.setOrder(member.getRecorder());
        return _member;
    }

    // 主数据
    private int insertTaskMain(String taskid, String taskName, Date begintime, String taskContent,
                               int contenttype, String address, String location, int userid) {
        int _result = 0;
        try {
            String _strSql =
                    " insert into crm_task( recid,recname,begintime,content,contenttype,address_name,address_location,reccreator) " +
                            " values(:recid,:recname,:begintime,:content,:contenttype,:address_name,:address_location,:reccreator) ";

            javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
            _query.setParameter("recid", taskid);
            _query.setParameter("recname", taskName);
            _query.setParameter("begintime", begintime);
            _query.setParameter("content", taskContent);
            _query.setParameter("contenttype", contenttype);
            _query.setParameter("address_name", address);
            _query.setParameter("address_location", location);
            _query.setParameter("reccreator", userid);

            _result = _query.executeUpdate();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    private int updateTaskMain(String taskid, String taskName, Date begintime, String taskContent,
                               int contenttype, String address, String location, int userid) {
        int _result = 0;
        try {
            String _strSql =
                    " update crm_task" +
                            " set recname=:recname, " +
                            " begintime=:begintime, " +
                            " content=:content, " +
                            " contenttype=:contenttype, " +
                            " address_name=:address_name, " +
                            " address_location=:address_location " +
                            " where recid=:recid ";

            javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
            _query.setParameter("recid", taskid);
            _query.setParameter("recname", taskName);
            _query.setParameter("begintime", begintime);
            _query.setParameter("content", taskContent);
            _query.setParameter("contenttype", contenttype);
            _query.setParameter("address_name", address);
            _query.setParameter("address_location", location);
            _result = _query.executeUpdate();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    //members
    private int insertTaskMember(String taskid, String groupid, List<TaskMember> members, int userid) {

        int _result = 0;
        String _strSql =
                " insert into crm_task_member( recid,taskid,groupid,userid,ismanager,ishost,reccreator,roleid,recorder)" +
                        " values(:recid,:taskid,:groupid,:userid,:ismanager,:ishost,:reccreator,0,:recorder)";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        List<TaskMember> _tmpMembers = new ArrayList<>();
        for (TaskMember member : members) {
            long _tmpCount = _tmpMembers.stream().filter(x -> x.getUserid() == member.getUserid()).count();
            if (_tmpCount == 0) {
                int _memberOrder = getMemberCount(taskid);
                _query.setParameter("recid", UUID.randomUUID().toString());
                _query.setParameter("taskid", taskid);
                _query.setParameter("groupid", groupid);
                _query.setParameter("userid", member.getUserid());
                _query.setParameter("ismanager", member.getIsmanager());
                _query.setParameter("ishost", member.getIshost());
                _query.setParameter("reccreator", userid);
                _query.setParameter("recorder", _memberOrder + 1);
                _result = _query.executeUpdate();
            }
            _tmpMembers.add(member);
        }
        return _result;
    }


    private int getMemberCount(String taskid) {
        String _strCountSql = " select count(1) from crm_task_member where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", taskid);
        int _memberOrder = getEntityCount(_strCountSql, _params);
        return _memberOrder;
    }

    //添加聊天聊天组
    private int insertChatGroup(String groupid, String groupName, String projectid, int stageid, int chatType,
                                int groupType, int userid,String color) {
        int _result = 0;
        String _strSql = " insert into crm_chat_group (recid,recname,objectid,stageid,chattype,grouptype,reccreator,color) " +
                " values(:recid,:recname,:objectid,:stageid,:chattype,:grouptype,:reccreator,:color)";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", groupid);
        _query.setParameter("recname", groupName);
        _query.setParameter("objectid", projectid);
        _query.setParameter("stageid", stageid);
        _query.setParameter("chattype", chatType);
        _query.setParameter("grouptype", groupType);
        _query.setParameter("reccreator", userid);
        _query.setParameter("color", color);
        _result = _query.executeUpdate();

        return _result;
    }


    public List<CrmTaskMember> getTaskMembers(String taskid) {

        String _strSql = " select m.recid,m.groupid,m.userid,m.roleid,m.ismanager,m.ishost,coalesce(u.realname,'') as username,m.reccreator,m.recorder " +
                "  from  crm_task_member m" +
                " inner join crm_user u on m.userid=u.id " +
                " where m.recstatus=1 " +
                " and  taskid=:taskid  order by m.createtime asc";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskMember.class);
        _query.setParameter("taskid", taskid);
        return _query.getResultList();
    }


    public int deleteTaskMember(String taskMemberid, int userid) {

        int _result = 0;
        String _strSql = " update crm_task_member set recstatus=0 where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskMemberid);
        _result = _query.executeUpdate();
        return _result;
    }

    //contacts
    public List<CrmTaskContact> getTaskContacts(String taskid) {

        String _strSql = " select recid,name,phone " +
                " from crm_task_contact " +
                " where recstatus=1 " +
                " and  taskid=:taskid ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskContact.class);
        _query.setParameter("taskid", taskid);
        return _query.getResultList();

    }

    public int deleteTaskContact(String taskContactid, int userid) {
        int _result = 0;
        String _strSql = " update crm_task_contact set recstatus=0 where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskContactid);
        _result = _query.executeUpdate();
        return _result;
    }


    public int insertTaskContact(String taskid, String name, String phone, int userid) {
        int _result = 0;

        try {
            String _strSql = " insert into crm_task_contact(recid,taskid,name,phone,reccreator)" +
                    "values(:recid,:taskid,:name,:phone,:reccreator) ";

            javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
            _query.setParameter("recid", UUID.randomUUID().toString());
            _query.setParameter("taskid", taskid);
            _query.setParameter("name", name);
            _query.setParameter("phone", phone);
            _query.setParameter("reccreator", userid);
            _result = _query.executeUpdate();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _result;
    }

    public int insertTaskContactBatch(String taskid, List<TaskContact> contacts, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (TaskContact _c : contacts) {
            _result = insertTaskContact(taskid, _c.getName(), _c.getPhone(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public int updateTaskContact(String recid, String name, String phone, int userid) {
        int _result = 0;
        String _strSql = " update crm_task_contact set name=:name,phone=:phone where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", recid);
        _query.setParameter("name", name);
        _query.setParameter("phone", phone);
        _result = _query.executeUpdate();
        return _result;
    }

    public int updateTaskContactBatch(List<TaskContact> contacts, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (TaskContact _c : contacts) {
            _result = updateTaskContact(_c.getRecid(), _c.getName(), _c.getPhone(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    // files
    public int insertTaskFile(String uuid, String taskid, String fileid, String filename, String sourceFileName, int userid) {

        int _result = 0;
        String _strSql = " insert into crm_task_file(recid,taskid,fileid,filename,file_suffix,reccreator,sourcefilename)" +
                " values(:recid,:taskid,:fileid,:filename,:file_suffix,:reccreator,:sourcefilename) ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", uuid);
        _query.setParameter("taskid", taskid);
        _query.setParameter("fileid", fileid);
        _query.setParameter("filename", filename);
        _query.setParameter("file_suffix", "");
        _query.setParameter("reccreator", userid);
        _query.setParameter("sourcefilename", sourceFileName);


        _result = _query.executeUpdate();

        return _result;
    }

    public int insertTaskFileBatch(String taskid, List<TaskFile> contacts, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (TaskFile _f : contacts) {
            String uuid = UUID.randomUUID().toString();
            _result = insertTaskFile(uuid, taskid, _f.getUploadfileid(), _f.getFilename(), _f.getSourcefilename(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public List<CrmTaskFile> getTaskFiles(String taskid) {

        String _strSql = " select t.recid,t.fileid,t.filename,t.file_suffix,coalesce(u.showfilename,'') as showfilename," +
                " t.reccreator,t.sourcefilename,t.sourcefilename,u2.realname as uploader,t.createtime,t.isviewed" +
                "  from crm_task_file t " +
                " left join crm_upload_file u on t.fileid=u.fileid" +
                " left join crm_user u2 on u2.id=t.reccreator " +
                " where t.recstatus=1 " +
                " and  t.taskid=:taskid " +
                " order by convert(filename using gbk)  asc ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskFile.class);
        _query.setParameter("taskid", taskid);
        return _query.getResultList();
    }

    public List<CrmTaskFile> getTaskFilesFilterStatus(String taskid, int status) {

        String _strSql = " select t.recid,t.fileid,t.filename,t.file_suffix,coalesce(u.showfilename,'') as showfilename," +
                " t.reccreator,t.sourcefilename,t.sourcefilename,u2.realname as uploader,t.createtime,t.isviewed" +
                "  from crm_task_file t " +
                " left join crm_upload_file u on t.fileid=u.fileid" +
                " left join crm_user u2 on u2.id=t.reccreator " +
                " where t.recstatus=:status " +
                " and  t.taskid=:taskid " +
                " order by convert(filename using gbk)  asc ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskFile.class);
        _query.setParameter("taskid", taskid);
        _query.setParameter("status", status);

        return _query.getResultList();
    }

    public List<CrmTaskFile> getTaskFiles(String taskid, int userid) {

        String _strSql = " select recid,fileid,filename,file_suffix,showfilename,reccreator,sourcefilename,isviewed,uploader,createtime " +
                " from ( select t.recid,t.fileid,t.filename,t.file_suffix,coalesce(u.showfilename,'') as showfilename," +
                " t.reccreator,t.sourcefilename,u2.realname as uploader,t.createtime," +
                " case  when h.recid is null then false else true end  as isviewed " +
                "  from crm_task_file t " +
                " left join crm_upload_file u on t.fileid=u.fileid" +
                " left join crm_user u2 on u2.id=t.reccreator " +
                " left join (select recid, filerecid, viewerid, recstatus, reccreator, createtime from crm_view_file_history where viewerid=:viewerid) h on t.recid=h.filerecid " +
                " where t.recstatus=1 " +
                " and  t.taskid=:taskid ) w " +
                " order by w.isviewed asc,w.createtime asc ";

        //,convert(w.filename using gbk) asc

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskFile.class);
        _query.setParameter("taskid", taskid);
        _query.setParameter("viewerid", userid);
        return _query.getResultList();
    }


    public int deleteTaskFile(String taskFileRecid, int userid) {

        int _result = 0;
        String _strSql = " update crm_task_file set recstatus=0 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", taskFileRecid);
        _result = updateEntity(_strSql, _params);
        return _result;
    }


    public int deleteTaskFileBatch(List<CrmTaskFile> contacts, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmTaskFile _r : contacts) {
            _result = deleteTaskFile(_r.getRecid(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    //reminders
    public List<CrmTaskReminder> getTaskReminders(String taskid) {

        String _strSql = " select recid,repeattype,reminder_minute,aheadtype,reccreator,taskid,0 as hasproject " +
                " from  crm_task_reminder " +
                "  where recstatus=1 " +
                " and taskid=:taskid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskReminder.class);
        _query.setParameter("taskid", taskid);
        return _query.getResultList();

    }

    public int insertTaskReminder(String recid, String taskid, int repeattype, int minutes, int aheadtype,
                                  int userid) {

        int _result = 0;
        String _strSql = " insert into crm_task_reminder(recid,taskid,repeattype,reminder_minute,reccreator,aheadtype)" +
                " values( :recid,:taskid,:repeattype,:reminder_minute,:reccreator,:aheadtype) ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", recid);
        _query.setParameter("taskid", taskid);
        _query.setParameter("repeattype", repeattype);
        _query.setParameter("reminder_minute", minutes);
        _query.setParameter("reccreator", userid);
        _query.setParameter("aheadtype", aheadtype);
        _result = _query.executeUpdate();

        return _result;
    }

    public int insertTaskReminderBatch(String taskid, List<TaskReminder> contacts, int userid) {
        int _result = 0;
        int _finalResult = 0;
        for (TaskReminder _r : contacts) {

            String _recid = UUID.randomUUID().toString();
            _result = insertTaskReminder(_recid, taskid, _r.getRepeattype(), _r.getAheadvalue(), _r.getAheadtype(), userid);
            _finalResult += _result;
        }
        return _finalResult;
    }

    public int deleteTaskReminder(String taskReminderid, int userid) {
        int _result = 0;
        String _strSql = " update crm_task_reminder set recstatus=0 where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskReminderid);
        _result = _query.executeUpdate();
        return _result;
    }


    public int updateTaskReminder(String taskReminderid, int repeattype, int minutes, int aheadtype, int userid) {

        int _result = 0;
        String _strSql = " update crm_task_reminder" +
                " set repeattype=:repeattype, " +
                " reminder_minute=:reminder_minute, " +
                " aheadtype=:aheadtype " +
                " where recid=:recid ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskReminderid);
        _query.setParameter("repeattype", repeattype);
        _query.setParameter("reminder_minute", minutes);
        _query.setParameter("aheadtype", aheadtype);

        _result = _query.executeUpdate();
        return _result;
    }


    //task
    public List<CrmTask> getTaskInfo(String taskid) {

        String _strSql = " select recid, recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime" +
                " from crm_task " +
                " where recid=:recid ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTask.class);
        _query.setParameter("recid", taskid);
        return _query.getResultList();
    }

    private TaskInfo toTaskInfo(CrmTask task) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TaskInfo _info = new TaskInfo();
        _info.setRecid(task.getRecid());
        _info.setTaskname(task.getRecname());
        String _strBeginTime = sdf.format(task.getBegintime());
        _info.setBegintime(_strBeginTime);
        _info.setContent(task.getContent());
        _info.setContenttype(task.getContenttype());
        _info.setAddressname(task.getAddressname());
        _info.setAddresslocation(task.getLocation());
        _info.setTaskstatus(task.getTaskstatus());


        return _info;
    }

    private TaskInfoList toTaskInfoList(CrmTask task) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TaskInfoList _info = new TaskInfoList();
        _info.setRecid(task.getRecid());
        _info.setTaskname(task.getRecname());
        String _strBeginTime = sdf.format(task.getBegintime());
        _info.setBegintime(_strBeginTime);
        _info.setContent(task.getContent());
        _info.setContenttype(task.getContenttype());
        _info.setAddressname(task.getAddressname());
        _info.setAddresslocation(task.getLocation());
        _info.setTaskstatus(task.getTaskstatus());


        return _info;
    }


    private TaskContact toTaskContact(CrmTaskContact contact) {
        TaskContact _contact = new TaskContact();
        _contact.setName(contact.getName());
        _contact.setPhone(contact.getPhone());
        _contact.setRecid(contact.getRecid());
        return _contact;
    }

    private TaskReminder toTaskReminder(CrmTaskReminder reminder) {
        TaskReminder _reminder = new TaskReminder();
        _reminder.setRecid(reminder.getRecid());
        _reminder.setAheadvalue(reminder.getMinutes());
        _reminder.setRepeattype(reminder.getRepeattype());
        _reminder.setAheadtype(reminder.getAheadtype());
        _reminder.setCreator(reminder.getReccreator());
        return _reminder;
    }

    private TaskFile toTaskFile(CrmTaskFile file) {
        TaskFile _file = new TaskFile();
        String _fileName = file.getFilename();
        _file.setRecid(file.getRecid());
        _file.setFilename(_fileName);
        _file.setUploadfileid(file.getFileid());
        String _fileSuffix = FilenameUtils.getExtension(_fileName);
        _file.setExtension(_fileSuffix);
        _file.setSourcefilename(file.getSourcefilename());
        _file.setIsviewed(file.getIsviewed());

        String _newFileName = file.getFileid();
        if (!_fileSuffix.isEmpty()) {
            _newFileName = _newFileName + "." + _fileSuffix;
        }
        _file.setNewfilename(_newFileName);
        _file.setShowfilename(file.getShowfilename());
        _file.setCreator(file.getReccreator());
        _file.setSourcefilename(file.getSourcefilename());
        _file.setUploader(file.getUploader());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        String _strUploadTime = df.format(file.getUploadtime());

        _file.setUploadtime(_strUploadTime);
        _file.setFileid(file.getRecid());

        return _file;
    }

    public List<CrmTaskAheadType> getTaskAheadType() {

        String _strSql = " select recid,recname,innertype,innervalue" +
                " from crm_task_reminder_ahead_type" +
                " where recstatus=1" +
                " order by recorder asc";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskAheadType.class);
        return _query.getResultList();


    }

    public List<CrmTaskRepeatType> getTaskRepeatType() {

        String _strSql = "select recid,recname,innertype " +
                " from  crm_task_reminder_repeat_type " +
                "  where recstatus=1 " +
                " order by recorder asc ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskRepeatType.class);
        return _query.getResultList();
    }

    public TaskAheadType toCrmTaskAheadType(CrmTaskAheadType aheadType) {
        TaskAheadType _aheadType = new TaskAheadType();
        _aheadType.setRecid(aheadType.getRecid());
        _aheadType.setRecname(aheadType.getRecname());
        _aheadType.setAheadtype(aheadType.getInnertype());
        _aheadType.setAheadvalue(aheadType.getInnervalue());
        return _aheadType;

    }

    public TaskRepeatType toTaskRepeatType(CrmTaskRepeatType repeatType) {
        TaskRepeatType _repeatType = new TaskRepeatType();
        _repeatType.setRecid(repeatType.getRecid());
        _repeatType.setRepeattype(repeatType.getInnertype());
        _repeatType.setRecname(repeatType.getRecname());
        return _repeatType;
    }

    public int deleteTask(String taskid, int userid) {

        int _result = 0;
        String _strSql = " update crm_task set recstatus=0 where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskid);
        _result = _query.executeUpdate();
        return _result;

    }

    public int completeTask(String taskid, int userid) {
        int _result = 0;
        String _strSql = " update crm_task set taskstatus=:taskstatus,completetime=now() where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskid);
        _query.setParameter("taskstatus", BaseEnum.TaskStatus.Complete.getTaskStatus());
        _result = _query.executeUpdate();
        return _result;
    }

    public int pauseTask(String taskid, int userid) {

        int _result = 0;
        String _strSql = " update crm_task set taskstatus=:taskstatus where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskid);
        _query.setParameter("taskstatus", BaseEnum.TaskStatus.Pause.getTaskStatus());
        _result = _query.executeUpdate();
        return _result;
    }

    public int restartTask(String taskid, int userid) {

        int _result = 0;
        String _strSql = " update crm_task set taskstatus=:taskstatus where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskid);
        _query.setParameter("taskstatus", BaseEnum.TaskStatus.Normal.getTaskStatus());
        _result = _query.executeUpdate();
        return _result;
    }

    public int transferManager(String taskMemberid, boolean isManager, int userid) {

        int _result = 0;
        String _strSql = " update crm_task_member set ismanager=:ismanager where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskMemberid);
        _query.setParameter("ismanager", isManager);
        _result = _query.executeUpdate();

        return _result;
    }

    public int transferHost(String taskMemberid, boolean isHost, int userid) {

        int _result = 0;
        String _strSql = " update crm_task_member set ishost=:ishost where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", taskMemberid);
        _query.setParameter("ishost", isHost);
        _result = _query.executeUpdate();
        return _result;

    }

    public List<CrmTaskSchedule> getTaskSchedulesBase() {
        String _strSql = " select recid,taskid,triggername,triggergroup,cronstring,begintime,reminderid " +
                " from crm_task_schedule where recstatus=1 ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskSchedule.class);
        return _query.getResultList();
    }

    public List<CrmTaskSchedule> getTaskSchedulesByTaskId(String taskid) {
        String _strSql = " select recid, taskid,triggername,triggergroup,cronstring,begintime,reminderid" +
                "  from crm_task_schedule " +
                " where recstatus=1 " +
                " and taskid=:taskid ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskSchedule.class);
        _query.setParameter("taskid", taskid);
        return _query.getResultList();
    }

    private int insertTaskSchedule(String recid, String taskid, String cronString, Date begintime, String
            reminderid, int userid) {

        int _result = 0;
        String _strSql =
                " insert into crm_task_schedule(recid,taskid,triggername,triggergroup,cronstring,reccreator,begintime,reminderid)" +
                        "  values(:recid,:taskid,:triggername,:triggergroup,:cronstring,:reccreator,:begintime,:reminderid) ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", recid);
        _query.setParameter("taskid", taskid);
        _query.setParameter("triggername", "taskTrigger");
        _query.setParameter("triggergroup", "taskTriggerGroup");
        _query.setParameter("cronstring", cronString);
        _query.setParameter("reccreator", userid);
        _query.setParameter("begintime", begintime);
        _query.setParameter("reminderid", reminderid);
        _result = _query.executeUpdate();

        return _result;
    }

    private int deleteTaskSchedule(String scheduleId) {

        int _result = 0;
        String _strSql = " update  crm_task_schedule set recstatus=0 where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", scheduleId);
        _result = _query.executeUpdate();

        return _result;
    }

    private int deleteTaskScheduleBatch(List<CrmTaskSchedule> schedules) {
        int _result = 0;
        int _finalResult = 0;
        for (CrmTaskSchedule s : schedules) {
            _result = deleteTaskSchedule(s.getRecid());
            _finalResult += _result;
        }
        return _finalResult;
    }


    private void insertQuartazSchedule(Scheduler scheduler, String taskid, String reminderId, String cronString, Date beginDateTime) throws Exception {


        JobDetail _job2 = JobBuilder.newJob(MyJob.class)
                .withDescription("任务定时job") //job的描述
                .withIdentity("taskJob" + reminderId, "taskJobGroup") //job 的name和group
                .build();


        _job2.getJobDataMap().put("reminderid", reminderId);
        _job2.getJobDataMap().put("taskid", taskid);


        Trigger _trigger2 = TriggerBuilder.newTrigger()
                .withDescription("")
                .withIdentity("taskTrigger" + reminderId, "taskTriggerGroup")
                .startAt(beginDateTime)  //设置开始时间
                .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                .build();

        scheduler.scheduleJob(_job2, _trigger2);


    }

    private void deleteQuartzSchedule(Scheduler scheduler, String reminderId) throws Exception {
        JobKey _key = new JobKey("taskJob" + reminderId, "taskJobGroup");
        scheduler.deleteJob(_key);

    }

    private TaskScheduleInfo createScheduleInfo(TaskReminder _r, Calendar cal) {


        //重复方式: 一次，每天，每周
        int _repeattype = _r.getRepeattype();

        //提前分钟数
        int _aheadValue = _r.getAheadvalue();

        //提前时间的类型：时，分，秒，天，
        int _aheadtype = _r.getAheadtype();

        //caculate schedule run time
        if (_aheadtype == BaseEnum.TaskAheadType.Minute.getTaskAheadType()) {
            cal.add(Calendar.MINUTE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Hour.getTaskAheadType()) {
            cal.add(Calendar.HOUR, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Day.getTaskAheadType()) {
            cal.add(Calendar.DATE, -_aheadValue);
        } else if (_aheadtype == BaseEnum.TaskAheadType.Month.getTaskAheadType()) {
            cal.add(Calendar.MONTH, -_aheadValue);
        }


        Date _scheduleStartDate = cal.getTime();

        int _year = cal.get(Calendar.YEAR);
        //calender 的月份从0 开始，所以要加1
        int _month = cal.get(Calendar.MONTH) + 1;
        int _day = cal.get(Calendar.DATE);
        int _hour = cal.get(Calendar.HOUR_OF_DAY);
        int _minute = cal.get(Calendar.MINUTE);
        int _second = cal.get(Calendar.SECOND);
        int _week = cal.get(Calendar.DAY_OF_WEEK);
        // _week = _week + 1;
        System.out.println("current week:" + _week);

        //create cron 表达式

        //把秒数设置为0
        _second = 0;

        String _cronString = String.format("0 %s %s %s %s ? %s", _minute, _hour, _day, _month, _year);

        if (_repeattype == BaseEnum.TaskRepeatType.Once.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s %s %s ? %s", _second, _minute, _hour, _day, _month, _year);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Day.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s * * ?", _second, _minute, _hour);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Week.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s ? * %s", _second, _minute, _hour, _week);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Month.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s %s * ?", _second, _minute, _hour, _day);
        } else if (_repeattype == BaseEnum.TaskRepeatType.Year.getTaskRepeatType()) {
            _cronString = String.format("%s %s %s %s %s ? *", _second, _minute, _hour, _day, _month);
        }


        TaskScheduleInfo _info = new TaskScheduleInfo();
        _info.setCronstring(_cronString);
        _info.setBegindatetime(_scheduleStartDate);

        return _info;
    }

    private int updateTaskSchedule(String recid, String cronString, Date begintime) {

        int _result = 0;
        String _strSql =
                " update crm_task_schedule " +
                        " set cronstring=:cronstring," +
                        " begintime=:begintime " +
                        " where recid=:recid ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", recid);
        _query.setParameter("cronstring", cronString);
        _query.setParameter("begintime", begintime);
        _result = _query.executeUpdate();

        return _result;
    }

    //添加任务关联项目
    private int insertTaskProjectRelation(String taskid, String projectid, int stageid, int userid) {

        int _result = 0;
        String _strSql = "insert into crm_project_task(recid,projectid,stageid,taskid,reccreator)" +
                "   values(:recid,:projectid,:stageid,:taskid,:reccreator) ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", UUID.randomUUID().toString());
        _query.setParameter("projectid", projectid);
        _query.setParameter("stageid", stageid);
        _query.setParameter("taskid", taskid);
        _query.setParameter("reccreator", userid);
        _result = _query.executeUpdate();

        return _result;
    }

    //get task project relation
    public List<CrmTaskProjectRelation> getTaskProjectRelation(String taskid) {

        String _strSql = " select recid,projectid,stageid" +
                " from crm_project_task " +
                " where recstatus=1 " +
                " and taskid is not null " +
                " and  taskid=:taskid ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskProjectRelation.class);
        _query.setParameter("taskid", taskid);
        return _query.getResultList();

    }

    public List<CrmProjectStageName> getProjectStageName(int stageid) {

        String _strSql = " select recid,recname from crm_project_stage where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmProjectStageName.class);
        _query.setParameter("recid", stageid);
        return _query.getResultList();

    }

    //更新任务成员
    private int updateTaskMember(List<TaskMember> members, int userid) {

        int _result = 0;
        String _strSql = " update crm_task_member set ismanager=:ismanager, ishost=:ishost,recorder=:recorder  where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        for (TaskMember member : members) {
            _query.setParameter("recid", member.getRecid());
            _query.setParameter("ismanager", member.getIsmanager());
            _query.setParameter("ishost", member.getIshost());
            _query.setParameter("recorder", member.getOrder());
            _result = _query.executeUpdate();
        }
        return _result;
    }

    public int updateTaskProjectRelation(String recid, String projectid, int stageid) {
        String _strSql = " update  crm_project_task set projectid=:projectid, stageid=:stageid,recstatus=1  where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql);
        _query.setParameter("recid", recid);
        _query.setParameter("projectid", projectid);
        _query.setParameter("stageid", stageid);
        return _query.executeUpdate();
    }


    public List<CrmTaskReminder> getReminders(String reminderid) {
        String _strSql = " select recid,taskid,repeattype,reminder_minute,aheadtype,reccreator, 0 as hasproject " +
                " from crm_task_reminder " +
                " where recid=:recid ";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTaskReminder.class);
        _query.setParameter("recid", reminderid);
        return _query.getResultList();
    }

    //发送任务的消息
    public void sendIMGroupMessageForTaskExtJsonObject(String taskid, String content, List<TaskMember> _taskMembers, int userid, JSONObject custExtJsonObject) {
        String _projectid = "";
        int _stageid = 0;
        String taskContent;
        List<CrmTask> tasks = getTaskInfo(taskid);
        taskContent = tasks.get(0).getContent();

        String _groupid = "";
        List<CrmTaskProjectRelation> _projectTasks = getTaskProjectRelation(taskid);
        if (_projectTasks != null && _projectTasks.size() > 0) {
            _projectid = _projectTasks.get(0).getProjectid();
            _stageid = _projectTasks.get(0).getStageid();
        }

        final int _finalStageId = _stageid;

        //use task chat group id
        List<CrmChatGroupPart> _groups = _commonRepository.getTaskChatGroup(taskid);
        if (_groups != null && _groups.size() > 0) {
            _groupid = _groups.get(0).getGroupid();
        }

        //List<TaskMember> _taskMembers = new ArrayList<>();
        boolean _isInClientChatGroup = false;
        boolean _isInLawyerChatGroup = false;
        if (_taskMembers != null) {
            List<CrmProjectMember> _projectMembers = _commonRepository.getProjectMember(_projectid, userid);
            if (_projectMembers != null) {

                List<CrmProjectMember> _projectClientMembers = _projectMembers.stream().filter(x -> x.getStageid() == _finalStageId &&
                        x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()
                        && x.getInnergrouptype() == BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType()).collect(Collectors.toList());

                List<CrmProjectMember> _projectLawyerMembers = _projectMembers.stream().filter(x -> x.getStageid() == _finalStageId &&
                        x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());

                for (TaskMember m : _taskMembers) {
                    long _theTaskMemberCount = _projectClientMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                    if (_theTaskMemberCount > 0) {
                        _isInClientChatGroup = true;
                        break;
                    }
                }
            }
        }

        //use project client chat group id
        String _clientGroupid = "";
        String _lawyerGroupid = "";
        if (!_projectid.isEmpty()) {
            _groups = _commonRepository.getProjectChatGroup(_projectid);
            if (_isInClientChatGroup) {
                Optional<CrmChatGroupPart> _theProjectClientChatGroup = _groups.stream().filter(x -> x.getStageid() == _finalStageId &&
                        x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();
                if (_theProjectClientChatGroup.isPresent()) {
                    _clientGroupid = _theProjectClientChatGroup.get().getGroupid();
                }
            }

            // if (_isInLawyerChatGroup) {
            Optional<CrmChatGroupPart> _theProjectLawyerChatGroup = _groups.stream().filter(x -> x.getStageid() == _finalStageId &&
                    x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();
            if (_theProjectLawyerChatGroup.isPresent()) {
                _lawyerGroupid = _theProjectLawyerChatGroup.get().getGroupid();
            }
            //  }
        }

        //send task chat group
        if (!_groupid.isEmpty()) {
            SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            String _strNow = _dataFormat.format(new Date());
            String _content = String.format("%s", content);

            String _title = taskContent;
            _imService.sendMessage(0, _groups.get(0).getGroupname(), _groupid, _title, _content, "text", "", null, custExtJsonObject, userid);
        }

        //send message to project client chat group
        if (!_clientGroupid.isEmpty()) {
            String _content = String.format("%s", content);

            List<CrmChatGroupPart> groups = _projectRepository.getChatGroupByGroupId(_clientGroupid);
            String _title = getMsgTitle(groups.get(0));
            _imService.sendMessage(0, groups.get(0).getGroupname(), _clientGroupid, _title, _content, "text", "", null, custExtJsonObject, userid);
        }

        //send to project lawyer chat group
        if (!_lawyerGroupid.isEmpty()) {
            String _content = String.format("%s", content);

            List<CrmChatGroupPart> groups = _projectRepository.getChatGroupByGroupId(_lawyerGroupid);
            String _title = getMsgTitle(groups.get(0));
            _imService.sendMessage(0, groups.get(0).getGroupname(), _lawyerGroupid, _title, _content, "text", "", null, custExtJsonObject, userid);
        }
    }

    public void sendIMGroupMessageForTask(String taskid, String content, List<TaskMember> _taskMembers, int userid, int pushFlag) {

        String _projectid = "";
        int _stageid = 0;
        String taskContent;
        List<CrmTask> tasks = getTaskInfo(taskid);
        taskContent = tasks.get(0).getContent();

        String _groupid = "";
        List<CrmTaskProjectRelation> _projectTasks = getTaskProjectRelation(taskid);
        if (_projectTasks != null && _projectTasks.size() > 0) {
            _projectid = _projectTasks.get(0).getProjectid();
            _stageid = _projectTasks.get(0).getStageid();
        }

        final int _finalStageId = _stageid;

        //use task chat group id
        List<CrmChatGroupPart> _groups = _commonRepository.getTaskChatGroup(taskid);
        if (_groups != null && _groups.size() > 0) {
            _groupid = _groups.get(0).getGroupid();
        }

        //List<TaskMember> _taskMembers = new ArrayList<>();
        boolean _isInClientChatGroup = false;
        boolean _isInLawyerChatGroup = false;
        if (_taskMembers != null) {
            List<CrmProjectMember> _projectMembers = _commonRepository.getProjectMember(_projectid, userid);
            if (_projectMembers != null) {

                List<CrmProjectMember> _projectClientMembers = _projectMembers.stream().filter(x -> x.getStageid() == _finalStageId &&
                        x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()
                        && x.getInnergrouptype() == BaseEnum.InnerGroupType.ClientGroup.getInnerGroupType()).collect(Collectors.toList());

                List<CrmProjectMember> _projectLawyerMembers = _projectMembers.stream().filter(x -> x.getStageid() == _finalStageId &&
                        x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());

                for (TaskMember m : _taskMembers) {
                    long _theTaskMemberCount = _projectClientMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                    if (_theTaskMemberCount > 0) {
                        _isInClientChatGroup = true;
                        break;
                    }
                }
            }
        }

        //use project client chat group id
        String _clientGroupid = "";
        String _lawyerGroupid = "";
        if (!_projectid.isEmpty()) {
            _groups = _commonRepository.getProjectChatGroup(_projectid);
            if (_isInClientChatGroup) {
                Optional<CrmChatGroupPart> _theProjectClientChatGroup = _groups.stream().filter(x -> x.getStageid() == _finalStageId &&
                        x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();
                if (_theProjectClientChatGroup.isPresent()) {
                    _clientGroupid = _theProjectClientChatGroup.get().getGroupid();
                }
            }

            // if (_isInLawyerChatGroup) {
            Optional<CrmChatGroupPart> _theProjectLawyerChatGroup = _groups.stream().filter(x -> x.getStageid() == _finalStageId &&
                    x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();
            if (_theProjectLawyerChatGroup.isPresent()) {
                _lawyerGroupid = _theProjectLawyerChatGroup.get().getGroupid();
            }
            //  }
        }

        //msg org
        JSONObject msgobj = new JSONObject();
        JSONObject data = new JSONObject();
        msgobj.put("type", "system");

        data.put("type", BaseEnum.ChatType.Task.getChatType());
        data.put("taskid", taskid);
        data.put("projectid", _projectid);
        msgobj.put("data", data);

        //没有关联项目阶段的任务才给任务群发消息
        //send task chat group
        if (!_groupid.isEmpty() && _projectid.isEmpty()) {
            SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            String _strNow = _dataFormat.format(new Date());
            String _content = String.format("%s", content);

            String _title = taskContent;
            _imService.sendMessage(pushFlag, _groups.get(0).getGroupname(), _groupid, _title, _content, "text", "", null, msgobj, userid);
        }

        //send message to project client chat group
        if (!_clientGroupid.isEmpty()) {
            String _content = String.format("%s", content);

            List<CrmChatGroupPart> groups = _projectRepository.getChatGroupByGroupId(_clientGroupid);
            String _title = getMsgTitle(groups.get(0));
            _imService.sendMessage(pushFlag, groups.get(0).getGroupname(), _clientGroupid, _title, _content, "text", "", null, msgobj, userid);
        }

        //send to project lawyer chat group
        if (!_lawyerGroupid.isEmpty()) {
            String _content = String.format("%s", content);

            List<CrmChatGroupPart> groups = _projectRepository.getChatGroupByGroupId(_lawyerGroupid);
            String _title = getMsgTitle(groups.get(0));
            _imService.sendMessage(pushFlag, groups.get(0).getGroupname(), _lawyerGroupid, _title, _content, "text", "", null, msgobj, userid);
        }
    }

    //just send im message
    public void sendIMMessage(String taskid, List<String> groupIds, String messageContent, int userid, int pushFlag) {

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        String _strNow = _dataFormat.format(new Date());
        for (String grouid : groupIds) {
            if (!grouid.isEmpty()) {
                String _content = String.format("%s", messageContent);
                List<CrmChatGroupPart> list = _projectRepository.getChatGroupByGroupId(grouid);
                CrmChatGroupPart groupTemp = list.get(0);
                if (groupTemp != null) {
                    String _title = "";
                    if (groupTemp.getChattype() == BaseEnum.ChatType.Task.getChatType())
                        _title = groupTemp.getTopicname();
                    else
                        _title = getMsgTitle(groupTemp);

                    //msg org
                    String _projectid = "";
                    List<CrmTaskProjectRelation> _projectTasks = getTaskProjectRelation(taskid);
                    if (_projectTasks != null && _projectTasks.size() > 0) {
                        _projectid = _projectTasks.get(0).getProjectid();
                    }

                    JSONObject msgobj = new JSONObject();
                    JSONObject data = new JSONObject();
                    msgobj.put("type", "system");
                    data.put("type", BaseEnum.ChatType.Task.getChatType());
                    data.put("taskid", taskid);
                    data.put("projectid", _projectid);
                    msgobj.put("data", data);
                    List<CrmChatGroupPart> groups = _projectRepository.getChatGroupByGroupId(grouid);
                    _imService.sendMessage(pushFlag, groups.get(0).getGroupname(), grouid, _title, _content, "text", "", null, msgobj, userid);
                }
            }
        }
    }

//    public void sendIMMessage_2(List<String> groupids, String content, int userid) {
//        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
//        if (groupids != null && groupids.size() > 0) {
//            for (String _groupid : groupids) {
//                if (!_groupid.isEmpty()) {
//                    String _strNow = _dataFormat.format(new Date());
//                    String _content = String.format("%s，%s", _strNow, content);
//                    _imService.sendMessage(_groupid, _content,"text","", userid);
//                }
//            }
//        }
//    }


    public void sendIMMessageWithFile(List<String> groupIds, String messageContent, String messageType, String extraData, JSONObject extJsonObject, int userid) {

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        String _strNow = _dataFormat.format(new Date());
        for (String grouid : groupIds) {
            if (!grouid.isEmpty()) {
                String _content = String.format("%s", messageContent);

                List<CrmChatGroupPart> list = _projectRepository.getChatGroupByGroupId(grouid);
                CrmChatGroupPart groupTemp = list.get(0);
                if (groupTemp != null) {
                    String _title = "";
                    if (groupTemp.getChattype() == BaseEnum.ChatType.Task.getChatType()) {
                        _title = groupTemp.getTopicname();
                    } else {
                        _title = getMsgTitle(groupTemp);
                    }
                    _imService.sendMessage(1, groupTemp.getGroupname(), grouid, _title, _content, messageType, extraData, extJsonObject, userid);
                }
            }
        }
    }

    public void sendIMMessageWithFile2(List<String> groupIds, String messageContent, String messageType, String extraData, JSONObject extJsonObject, int userid) {

        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        String _strNow = _dataFormat.format(new Date());
        for (String grouid : groupIds) {
            if (!grouid.isEmpty()) {
                String _content = String.format("%s", messageContent);

                List<CrmChatGroupPart> list = _projectRepository.getChatGroupByGroupId(grouid);
                CrmChatGroupPart groupTemp = list.get(0);
                if (groupTemp != null) {
                    String _title = "";
                    if (groupTemp.getChattype() == BaseEnum.ChatType.Task.getChatType()) {
                        _title = groupTemp.getTopicname();
                    } else {
                        _title = getMsgTitle(groupTemp);
                    }
                    _imService.sendMessage2(1, groupTemp.getGroupname(), grouid, _title, _content, messageType, extraData, extJsonObject, userid);
                }
            }
        }
    }

    private String getMsgTitle(CrmChatGroupPart group) {
        String _title = "律协";
        if (group.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType())
            _title = "委协";
        _title = String.format("%s-%s", _title, group.getTopicname());

        return _title;
    }

    private void insertQuartazSchedule(Scheduler scheduler, String taskid, TaskInfo info, String reminderId, String cronString, Date beginDateTime) throws Exception {


        JobDetail _job2 = JobBuilder.newJob(MyJob.class)
                .withDescription("任务定时job") //job的描述
                .withIdentity("taskJob" + reminderId, "taskJobGroup") //job 的name和group
                .build();


        _job2.getJobDataMap().put("reminderid", reminderId);
        _job2.getJobDataMap().put("taskid", taskid);
        _job2.getJobDataMap().put("taskcontent", info.getContent());
        _job2.getJobDataMap().put("taskbegintime", info.getBegintime());
        _job2.getJobDataMap().put("taskaddress", info.getAddressname());


        Trigger _trigger2 = TriggerBuilder.newTrigger()
                .withDescription("")
                .withIdentity("taskTrigger" + reminderId, "taskTriggerGroup")
                .startAt(beginDateTime)  //设置开始时间
                .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                .build();

        scheduler.scheduleJob(_job2, _trigger2);


    }


    public int deleteTaskProjectRelation(String relateid) {
        String _strSql = " update crm_project_task set recstatus=0 where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", relateid);
        return updateEntity(_strSql, _params);
    }


    public int updateTaskInfo_test(SaveTaskInfoRequest _request, int userid) throws Exception {

        int _result = 1;
        return _result;
    }

    @Transactional
    public ResultResponse updateTaskInfo(SaveTaskInfoRequest _request, int userid) throws Exception {

        ResultResponse _resultResponse = new ResultResponse();
        int _result = 0;
        String _stageName = "";
        String _projectName = "";

        String _taskid = _request.getRecid();
        String _taskContent = _request.getContent();
        String _strBeginTime = _request.getBegintime();
        //  int _contenttype = _request.getContenttype();
        String _requestAddress = _request.getAddressname();
        String _location = _request.getAddresslocation();
        String _projectid = _request.getProjectid();
        //群组加颜色标记
        String color= RandomColorGenerator.getRandomRGB16();

        int _requestStageId = _request.getStageid();

        if (_projectid == null) {
            _projectid = "";
        }

        List<CrmTaskMember> _taskMembers = getTaskMembers(_taskid);
        List<TaskMember> _taskMemberResponse = new ArrayList<>();
        for (CrmTaskMember m : _taskMembers) {
            TaskMember _tm = toCrmTaskMember(m);
            _taskMemberResponse.add(_tm);
        }

        if (!_projectid.isEmpty()) {
            // check if the task member include members out of the project stage members.
            List<String> _taskOnlyMember = new ArrayList<>();

            List<CrmProjectMember> _projectMembers = _commonRepository.getProjectStagetMember(_projectid, _requestStageId, userid);
            for (CrmTaskMember m : _taskMembers) {
                long _theCount = _projectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                if (_theCount == 0) {
                    _taskOnlyMember.add(m.getUsername());
                }
            }

            List<CrmProjectStage> _projectStages = _commonRepository.getProjectStage(_requestStageId);
            if (_projectStages != null && _projectStages.size() > 0) {
                _stageName = _projectStages.get(0).getStagename();
            }

            if (_taskOnlyMember.size() > 0) {
                String _userNames = StringUtils.join(_taskOnlyMember.toArray(), ",");

                List<CrmProject> _projects = _commonRepository.getProject(_projectid);
                if (_projects != null && _projects.size() > 0) {
                    _projectName = _projects.get(0).getRecname();
                }

                String _errorMessage = String.format("请先将%s添加到%s项目的%s阶段!", _userNames, _projectName, _stageName);
                _resultResponse.setMessage(_errorMessage);
                _resultResponse.setResultcode(-1);
                return _resultResponse;
            }
        } else {
            CrmChatGroup _taskChatGroup = getTaskChatGroup(_taskid);
            if (_taskChatGroup != null) {
                String _theTaskChatGroupId = _taskChatGroup.getGroupid();

                //设置聊天组可以发送聊天消息
                setTaskChatGroupActive(_theTaskChatGroupId, true);
            }
        }


        List<CrmTask> _tasks = getTaskInfo(_taskid);

        //old contacts of info
        List<CrmTaskContact> _savedContacts = getTaskContacts(_taskid);

        //获取关联项目数据
        List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(_taskid);
        if (_relations != null && _relations.size() > 0) {
            CrmTaskProjectRelation _currentRelation = _relations.get(0);
            String _recid = _currentRelation.getRecid();
            String _savedProjectid = _currentRelation.getProjectid();
            int _savedStageid = _currentRelation.getStageid();

            if (!_projectid.isEmpty()) {
                if (!_projectid.equals(_savedProjectid) || _savedStageid != _requestStageId) {
                    updateTaskProjectRelation(_recid, _projectid, _requestStageId);
                }
            } else {

                //delete project task relation
                deleteTaskProjectRelation(_recid);

                CrmChatGroup _taskChatGroup = getTaskChatGroup(_taskid);
                if (_taskChatGroup != null) {
                    String _theTaskChatGroupId = _taskChatGroup.getGroupid();

                    //设置聊天组为可以发送聊天消息
                    setTaskChatGroupActive(_theTaskChatGroupId, true);
                } else {

                    //新建聊天组,把成员添加的到聊天组
                    int _stageid = 0;
                    int _chatType = BaseEnum.ChatType.Task.getChatType();
                    String _taskChatGroupId = UUID.randomUUID().toString();
                    createTaskChatGroup(_taskid, _taskContent, _stageid, _chatType, _taskChatGroupId, _taskMemberResponse, userid,color);
                }
            }
        } else {

            if (!_projectid.isEmpty()) {
                insertTaskProjectRelation(_taskid, _projectid, _requestStageId, userid);
                //disaction task chat group
                CrmChatGroup _taskChatGroup = getTaskChatGroup(_taskid);
                if (_taskChatGroup != null) {
                    String _theTaskChatGroupId = _taskChatGroup.getGroupid();

                    //设置聊天组为不可以发送聊天消息
                    setTaskChatGroupActive(_theTaskChatGroupId, false);
                }

            } else {

                CrmChatGroup _taskChatGroup = getTaskChatGroup(_taskid);
                if (_taskChatGroup != null) {
                    String _theTaskChatGroupId = _taskChatGroup.getGroupid();

                    //设置聊天组为可以发送聊天消息
                    setTaskChatGroupActive(_theTaskChatGroupId, true);
                } else {
                    //新建聊天组,把成员添加的到聊天组
                    int _stageid = 0;
                    int _chatType = BaseEnum.ChatType.Task.getChatType();
                    String _taskChatGroupId = UUID.randomUUID().toString();
                    createTaskChatGroup(_taskid, _taskContent, _stageid, _chatType, _taskChatGroupId, _taskMemberResponse, userid,color);
                }
            }
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date _beginTime = df.parse(_strBeginTime);

        //更新任务主数据
        _result = updateTaskMain(_taskid, "", _beginTime, _taskContent, 0, _requestAddress, _location, userid);

        //====任务联系人
        List<TaskContact> _contacts = _request.getContacts();

        //更新老的联系人
        List<TaskContact> _oldContacts = _contacts.stream().filter(x -> x.getRecid() != null && !x.getRecid().equals("")).collect(Collectors.toList());
        updateTaskContactBatch(_oldContacts, userid);

        //删除老的联系人
        for (CrmTaskContact _c : _savedContacts) {
            List<TaskContact> _tmp = _oldContacts.stream().filter(x -> x.getRecid().equals(_c.getRecid())).collect(Collectors.toList());
            if (_tmp == null || _tmp.size() == 0) {
                deleteTaskContact(_c.getRecid(), userid);
            }
        }

        //添加新增的联系人
        List<TaskContact> _newContacts = _contacts.stream().filter(x -> x.getRecid() == null || x.getRecid().equals("")).collect(Collectors.toList());
        insertTaskContactBatch(_taskid, _newContacts, userid);


        //如果开始时间变化，需要更新schedule
        List<CrmTask> _savedTasks = getTaskInfo(_taskid);
        if (_savedTasks != null && _savedTasks.size() > 0) {
            Date _taskBeginTime = _savedTasks.get(0).getBegintime();

            //如果开始时间改变了
            if (!_taskBeginTime.equals(_beginTime)) {

                //update reminder
                List<CrmTaskSchedule> _savedSchedules = getTaskSchedulesByTaskId(_taskid);
                List<CrmTaskReminder> _savedTaskReminders = getTaskReminders(_taskid);

                TaskInfo _info = new TaskInfo();
                _info.setContent(_taskContent);
                _info.setAddressname(_requestAddress);
                _info.setBegintime(_strBeginTime);


                Calendar cal = Calendar.getInstance();
                cal.setTime(_taskBeginTime);
                Scheduler _scheduler = StdSchedulerFactory.getDefaultScheduler();
                for (CrmTaskReminder r : _savedTaskReminders) {

                    String _reminderId = r.getRecid();
                    int _repeatType = r.getRepeattype();
                    int _aheadValue = r.getMinutes();
                    int _aheadType = r.getAheadtype();


                    TaskReminder _reminder = toTaskReminder(r);

                    TaskScheduleInfo _scheduleInfo = createScheduleInfo(_reminder, cal);
                    String _cronString = _scheduleInfo.getCronstring();
                    Date _beginDateTime = _scheduleInfo.getBegindatetime();

                    //delete running schedule
                    deleteQuartzSchedule(_scheduler, _reminderId);

                    //delete schedule data
                    List<CrmTaskSchedule> _tmpSchedules = _savedSchedules.stream().filter(x -> x.getReminderid() != null
                            && x.getReminderid().equals(r.getRecid())).collect(Collectors.toList());
                    deleteTaskScheduleBatch(_tmpSchedules);

                    //add running schedule
                    insertQuartazSchedule(_scheduler, _taskid, _info, _reminderId, _cronString, _beginDateTime);

                    //add schedule data
                    String _scheduleId = UUID.randomUUID().toString();
                    insertTaskSchedule(_scheduleId, _taskid, _cronString, _beginDateTime, _reminderId, userid);

                }
            }
        }


        /**
         * send system message for changed
         */

        try {
            //check if info changed ,then send message
            boolean _isInfoChanged = false;
            boolean _isReminderChanged = false;
            boolean _isFileChanged = false;
            boolean _isMemberChanged = false;
            //联系人是否变化
            boolean _isContactChanged = false;
            //阶段是否变化
            boolean _isStageChanged = false;
            boolean _isTaskContentChanged = false;
            boolean _isAddressChanged = false;
            boolean _isBeginTimeChanged = false;

            //检查信息是否发生了改变
            //关联项目
            String _savedContent = "";
            Date _savedTaskBeginTime = null;
            String _savedTaskAddress = null;
            if (_tasks != null && _tasks.size() > 0) {
                CrmTask _currentTaskIfo = _tasks.get(0);
                _savedContent = _currentTaskIfo.getContent();
                _savedTaskBeginTime = _currentTaskIfo.getBegintime();
                _savedTaskAddress = _currentTaskIfo.getAddressname();
            }

            //更新群组的名称
            if (_projectid == null || _projectid == "") {
                if (_relations == null || _relations.size() == 0) {
                    if (!_savedContent.equals(_taskContent)) {
                        CrmChatGroup _taskChatGroup = getTaskChatGroup(_taskid);
                        if (_taskChatGroup != null) {
                            String _theChatGroupId = _taskChatGroup.getGroupid();
                            String _theGroupName = _taskContent;
                            String _roupIntroduction = _taskContent;
                            if (_theGroupName.length() > 10) {
                                _theGroupName = _theGroupName.substring(0, 10);
                            }

                            if (_taskContent.length() > 100) {
                                _roupIntroduction = _taskContent.substring(0, 100);
                            }

                            _imService.updataeIMGroup(_theChatGroupId, _theGroupName, _roupIntroduction, userid);
                        }
                    }
                }
            }

            // ---------------
            SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String _savedBeginTime = _dataFormat.format(_savedTaskBeginTime);
            if (!_savedBeginTime.equals(_strBeginTime)) {
                _isInfoChanged = true;
                _isBeginTimeChanged = true;
            }

            if (!_savedContent.equals(_taskContent)) {
                _isInfoChanged = true;
                _isTaskContentChanged = true;
            }

            if (_relations != null && _relations.size() > 0) {
                int _theStageid = _relations.get(0).getStageid();
                String _theProjectid = _relations.get(0).getProjectid();
                if (!_theProjectid.equals(_projectid) || _theStageid != _request.getStageid()) {
                    _isInfoChanged = true;
                    _isStageChanged = true;
                }
            } else {
                if (!_projectid.isEmpty() && _request.getStageid() > 0) {
                    _isInfoChanged = true;
                    _isStageChanged = true;
                }
            }
            //------------------
            // is project id or stage id changed
//            if (!_isInfoChanged) {
//                if (_relations != null && _relations.size() > 0) {
//                    int _theStageid = _relations.get(0).getStageid();
//                    String _theProjectid = _relations.get(0).getProjectid();
//                    if (!_theProjectid.equals(_projectid) || _theStageid != _request.getStageid()) {
//                        _isInfoChanged = true;
//                        _isStageChanged = true;
//                    }
//                } else {
//                    if (!_projectid.isEmpty() && _request.getStageid() > 0) {
//                        _isInfoChanged = true;
//                        _isStageChanged = true;
//                    }
//                }
//            }

            //is task content changed
//            if (!_isInfoChanged) {
//                if (!_savedContent.equals(_taskContent)) {
//                    _isInfoChanged = true;
//                    _isTaskContentChanged = true;
//                }
//            }

            //is task begin time changed
//            if (!_isInfoChanged) {
//                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String _savedBeginTime = _dataFormat.format(_savedTaskBeginTime);
//                if (!_savedBeginTime.equals(_strBeginTime)) {
//                    _isInfoChanged = true;
//                    _isBeginTimeChanged = true;
//                }
//            }

            //is task address chanaged
            if (_savedTaskAddress != null && _requestAddress != null) {
                if (!_savedTaskAddress.equals(_requestAddress)) {
                    _isInfoChanged = true;
                    _isAddressChanged = true;
                } else {
                    if ((_savedTaskAddress == null || _savedTaskAddress.isEmpty()) && (_requestAddress != null && !_requestAddress.isEmpty())) {
                        _isInfoChanged = true;
                        _isAddressChanged = true;
                    }
                    if ((_savedTaskAddress != null && !_savedTaskAddress.isEmpty()) && (_requestAddress == null || _requestAddress.isEmpty())) {
                        _isInfoChanged = true;
                        _isAddressChanged = true;
                    }
                }
            }

            //is task contact changed
            if (_contacts != null && _contacts.size() > 0) {
                if (_savedContacts != null) {
                    if (_contacts.size() != _savedContacts.size()) {
                        _isInfoChanged = true;
                        _isContactChanged = true;
                    }
                    for (TaskContact c : _contacts) {
                        long _theContactCount = _savedContacts.stream().filter(x -> x.getName().equals(c.getName())
                                && x.getPhone().equals(c.getPhone())).count();
                        if (_theContactCount == 0) {
                            _isInfoChanged = true;
                            _isContactChanged = true;
                            break;
                        }
                    }
                } else {
                    _isInfoChanged = true;
                    _isContactChanged = true;
                }
            } else {
                if (_savedContacts != null && _savedContacts.size() > 0) {
                    _isInfoChanged = true;
                    _isContactChanged = true;
                }
            }

            if (_savedContacts != null && _savedContacts.size() > 0) {
                for (CrmTaskContact c : _savedContacts) {
                    long _theContactCount = _contacts.stream().filter(x -> x.getName().equals(c.getName()) && x.getPhone().equals(c.getPhone())).count();
                    if (_theContactCount == 0) {
                        _isInfoChanged = true;
                        _isContactChanged = true;
                    }
                }
            } else {
                if (_contacts != null && _contacts.size() > 0) {
                    _isInfoChanged = true;
                    _isContactChanged = true;
                }
            }

            if (_isInfoChanged) {
                CrmUser _theUser = _commonRepository.getUserInfo(userid);
                List<String> _messageContent = new ArrayList<>();
                List<String> _messageContentTask = new ArrayList<>();
                List<CrmProject> _projects = _commonRepository.getProject(_projectid);
                if (_projects != null && _projects.size() > 0) {
                    _projectName = _projects.get(0).getRecname();
                }
                String name = "【" + _stageName + "】" + _projectName;
                if (_isStageChanged) {
                    if (_relations != null && _relations.size() > 0) {
                        if (!_projectid.isEmpty()) {
                            //关联了项目的任务->关联了项目的任务
                            String _content = String.format("%s修改了任务：%s，关联项目阶段为：%s", _theUser.getRealname(), _taskContent, name);
                            _messageContent.add(_content);
                        } else {
                            //关联了项目的任务->取消关联了项目的任务
                            String _content = String.format("%s修改了任务：%s，关联项目阶段为：空", _theUser.getRealname(), _taskContent);
                            _messageContent.add(_content);
                        }
                    } else {
                        if (!_projectid.isEmpty()) {
                            //无关联了项目的任务->关联了项目的任务
                            String _content = String.format("%s修改了任务：%s，关联项目阶段为：%s", _theUser.getRealname(), _taskContent, name);
                            _messageContent.add(_content);

                            String _contentTask = String.format("该任务已关联项目阶段：%s，如需沟通，请到项目阶段群聊里进行", name);
                            _messageContentTask.add(_contentTask);
                        } else {
                            //无关联了项目的任务->无关联了项目的任务
                            //这里不需要发消息
                        }
                    }
                }

                //任务内容
                if (_isTaskContentChanged) {
                    if (!_projectid.isEmpty()) {
                        String _content = String.format("%s修改了任务：%s，任务内容为：%s", _theUser.getRealname(), _taskContent, _taskContent);
                        _messageContent.add(_content);
                    } else {
                        String _content = String.format("%s修改了任务内容为：%s", _theUser.getRealname(), _taskContent);
                        _messageContent.add(_content);
                    }
                }
                //任务开始时间
                if (_isBeginTimeChanged) {
                    SimpleDateFormat _dataFormat_ = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date _strToDate = _dataFormat_.parse(_strBeginTime);
                    String taskBegintime = _dataFormat_.format(_strToDate);
                    if (!_projectid.isEmpty()) {
                        String _content = String.format("%s修改了任务：%s，开始时间为：%s", _theUser.getRealname(), _taskContent, taskBegintime);
                        _messageContent.add(_content);
                    } else {
                        String _content = String.format("%s修改了任务开始时间为：%s", _theUser.getRealname(), taskBegintime);
                        _messageContent.add(_content);
                    }
                }
                //任务地点
                if (_isAddressChanged) {
                    if (!_projectid.isEmpty()) {
                        String _content = String.format("%s修改了任务：%s，任务地点为：%s", _theUser.getRealname(), _taskContent, _requestAddress);
                        _messageContent.add(_content);
                    } else {
                        String _content = String.format("%s修改了任务地点为：%s", _theUser.getRealname(), _requestAddress);
                        _messageContent.add(_content);
                    }
                }
                //联系人
                if (_isContactChanged == true) {
                    if (_contacts != null && _contacts.size() > 0) {
                        String names = _contacts.stream().map(TaskContact::getName).collect(Collectors.joining(","));
                        if (!_projectid.isEmpty()) {
                            String _content = String.format("%s修改了任务：%s，联系人为：%s", _theUser.getRealname(), _taskContent, names);
                            _messageContent.add(_content);
                        } else {
                            String _content = String.format("%s修改了联系人为：%s", _theUser.getRealname(), names);
                            _messageContent.add(_content);
                        }
                    } else {
                        if (!_projectid.isEmpty()) {
                            String _content = String.format("%s修改了任务：%s，清空了联系人", _theUser.getRealname(), _taskContent);
                            _messageContent.add(_content);
                        } else {
                            String _content = String.format("%s清空了联系人", _theUser.getRealname());
                            _messageContent.add(_content);
                        }
                    }
                }
                //TODO 消息处理
                // 有项目->没有项目 原项目以及新任务发消息
                // 有项目->有项目
                List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
                for (String _message : _messageContent) {
                    if (!_message.isEmpty()) {
                        sendIMMessage(_taskid, _chatGroupIds, _message, userid, 0);
                    }
                }

                //单独发到任务群
                if (_messageContentTask != null && _messageContentTask.size() > 0) {
                    List<String> _chatGroupIdsTask = new ArrayList<>();
                    List<CrmChatGroupPart> _taskChatGroup = _commonRepository.getTaskChatGroup(_taskid);
                    if (_taskChatGroup != null && _taskChatGroup.size() > 0) {
                        _chatGroupIdsTask.add(_taskChatGroup.get(0).getGroupid());
                    }
                    for (String _message : _messageContentTask) {
                        if (!_message.isEmpty()) {
                            sendIMMessage(_taskid, _chatGroupIdsTask, _message, userid, 0);
                        }
                    }
                }
            }
            //  2022/4/28 修改开始时间,发送消息通知
            if (_isBeginTimeChanged) {
                List<CrmTaskMember> taskMembers = getTaskMembers(_taskid);
                List<Integer> userIdList = taskMembers.stream().filter(m -> m.getUserid() != userid).map(CrmTaskMember::getUserid).collect(Collectors.toList());
                if (!userIdList.isEmpty()) {
                    List<String> phones = getPhoneByIds(userIdList);
                    logger.info("修改开始时间,发送消息通知." + phones);
                    smsDanMiService.updateStartTime(phones);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        _resultResponse.setMessage("");
        _resultResponse.setResultcode(_result);
        return _resultResponse;
    }

    @Transactional
    public int saveTaskReminder(SaveTaskReminderRequest _request, int userid) throws Exception {

        int _result = 0;

        String _taskid = _request.getTaskid();

        Scheduler _scheduler = StdSchedulerFactory.getDefaultScheduler();
        List<TaskReminder> _reminders = _request.getReminders();
        List<CrmTaskSchedule> _savedSchedules = getTaskSchedulesByTaskId(_taskid);
        List<CrmTaskReminder> _savedTaskReminders = getTaskReminders(_taskid);

        String _strTaskBeginTime = "";
        String _addressName = "";
        String _taskContent = "";
        Date _taskBeginTime = new Date();
        List<CrmTask> _savedTasks = getTaskInfo(_taskid);
        if (_savedTasks != null && _savedTasks.size() > 0) {
            _taskBeginTime = _savedTasks.get(0).getBegintime();
            _addressName = _savedTasks.get(0).getAddressname();
            _taskContent = _savedTasks.get(0).getContent();
        }

        TaskInfo _info = new TaskInfo();
        _info.setContent(_taskContent);
        _info.setAddressname(_addressName);
        //set task begin time
        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String _strBeginTime = _dataFormat.format(_taskBeginTime);
        _info.setBegintime(_strBeginTime);

        Calendar cal = Calendar.getInstance();
        for (TaskReminder r : _reminders) {
            cal.setTime(_taskBeginTime);
            List<CrmTaskReminder> _theTempReminders = _savedTaskReminders.stream().filter(
                    x -> x.getRepeattype() == r.getRepeattype()
                            && x.getAheadtype() == r.getAheadtype()
                            && x.getMinutes() == r.getAheadvalue()).collect(Collectors.toList());

            //insert new reminder
            long _theReminderCount = _theTempReminders.size();
            TaskScheduleInfo _scheduleInfo = createScheduleInfo(r, cal);
            String _cronString = _scheduleInfo.getCronstring();
            Date _beginDateTime = _scheduleInfo.getBegindatetime();
            if (_theReminderCount == 0) {
                // insert reminder
                String _reminderId = UUID.randomUUID().toString();

                //insert reminder data
                int _repeatType = r.getRepeattype();
                int _aheadValue = r.getAheadvalue();
                int _aheadType = r.getAheadtype();
                insertTaskReminder(_reminderId, _taskid, _repeatType, _aheadValue, _aheadType, userid);

                //add running schedule
                //insertQuartazSchedule(_scheduler, _taskid, _info, _reminderId, _cronString, _beginDateTime);

                //add schedule data
                // String _scheduleId = UUID.randomUUID().toString();
                // insertTaskSchedule(_scheduleId, _taskid, _cronString, _beginDateTime, _reminderId, userid);
            }
        }

        //delete removed reminder
        for (CrmTaskReminder r : _savedTaskReminders) {
            long _theReminderCount = _reminders.stream().filter(
                    x -> x.getRepeattype() == r.getRepeattype()
                            && x.getAheadtype() == r.getAheadtype()
                            && x.getAheadvalue() == r.getMinutes()).count();

            if (_theReminderCount == 0) {

                //delete reminder
                deleteTaskReminder(r.getRecid(), userid);

                //delete running schedule
                //deleteQuartzSchedule(_scheduler, r.getRecid());

                //delete schedule data
                    /*List<CrmTaskSchedule> _tmpSchedules = _savedSchedules.stream().filter(x -> x.getReminderid() != null
                            && x.getReminderid().equals(r.getRecid())).collect(Collectors.toList());
                    deleteTaskScheduleBatch(_tmpSchedules);
                    */
            }
        }

        /**
         * send system message
         */
        try {
            boolean _isReminderChanged = false;
            if (_reminders != null && _reminders.size() > 0) {
                if (_savedTaskReminders != null && _savedTaskReminders.size() > 0) {
                    if (_savedTaskReminders.size() == _reminders.size()) {
                        long _theReminderCount = _reminders.stream().filter(x -> x.getRecid() == null || x.getRecid().isEmpty()).count();
                        if (_theReminderCount > 0) {
                            _isReminderChanged = true;
                        } else {
                            for (CrmTaskReminder r : _savedTaskReminders) {
                                long _theCount = _reminders.stream().filter(x -> x.getRepeattype() == r.getRepeattype()
                                        && x.getAheadtype() == r.getAheadtype() && x.getAheadvalue() == r.getMinutes()).count();
                                if (_theCount == 0) {
                                    _isReminderChanged = true;
                                }
                            }
                        }
                    } else {
                        _isReminderChanged = true;
                    }

                } else {
                    _isReminderChanged = true;
                }
            } else {
                if (_savedTaskReminders != null && _savedTaskReminders.size() > 0) {
                    _isReminderChanged = true;
                }
            }

            if (_isReminderChanged) {
                List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(_taskid);
                CrmUser _theUser = _commonRepository.getUserInfo(userid);
                List<String> _messageContent = new ArrayList<>();
                if (_relations != null && _relations.size() > 0) {
                    //关联了项目的任务
                    String names = _reminders.stream().map(TaskReminder::calAheadType).collect(Collectors.joining(","));
                    String _content = String.format("%s修改了任务：%s，提醒为：%s", _theUser.getRealname(), _taskContent, names);
                    _messageContent.add(_content);
                } else {
                    //无关联了项目的任务
                    String names = _reminders.stream().map(TaskReminder::calAheadType).collect(Collectors.joining(","));
                    String _content = String.format("%s修改了提醒为：%s：", _theUser.getRealname(), names);
                    _messageContent.add(_content);
                }

                List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
                for (String _message : _messageContent) {
                    if (!_message.isEmpty()) {
                        sendIMMessage(_taskid, _chatGroupIds, _message, userid, 0);
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }


        return 1;
    }

    public List<GetTaskForSpecialDayListResponse> getTaskForSepcialDay(int userid) throws Exception {

        int _year = 0;
        int _month = 0;
        int _day = 0;

        String _strSql = "select recid, recname, begintime, content, contenttype, address_name, address_location, " +
                "taskstatus, completetime, recstatus, createtime, reccreator " +
                " from crm_task  " +
                " where recstatus=1  " +
                " and  recid in (select taskid   from crm_task_member where recstatus=1 and userid=:userid)";

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);

        List<CrmTask> _tasks = getEntitys(_strSql, _params, CrmTask.class);

        //获取唯一的年月日
        Calendar cal = Calendar.getInstance();
        List<TaskBeginTimeItem> _items = new ArrayList<>();
        for (CrmTask t : _tasks) {
            cal.setTime(t.getBegintime());
            _year = cal.get(Calendar.YEAR);
            _month = cal.get(Calendar.MONTH) + 1;
            _day = cal.get(Calendar.DATE);

            TaskBeginTimeItem _theItem = new TaskBeginTimeItem();
            _theItem.setYear(_year);
            _theItem.setMonth(_month);
            _theItem.setDay(_day);

            if (!_items.contains(_theItem)) {
                _items.add(_theItem);
            }
        }

        List<GetTaskForSpecialDayListResponse> _infos = new ArrayList<>();


        //过滤task
        SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (TaskBeginTimeItem t : _items) {
            GetTaskForSpecialDayListResponse _theDayTask = new GetTaskForSpecialDayListResponse();
            String _strMonth = String.format("%02d", t.getMonth());
            String _strDay = String.format("%02d", t.getDay());
            String _theYearString = String.format("%s-%s-%s", t.getYear(), _strMonth, _strDay);
            _theDayTask.setTaskbegintime(_theYearString);

            List<CrmTask> _theDayTasks = _tasks.stream().filter(x -> _dataFormat.format(x.getBegintime()).equals(_theYearString)).collect(Collectors.toList());
            List<GetTaskForSpecialDayListItemResponse> _theTasks = new ArrayList<>();
            SimpleDateFormat _simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (_theDayTasks != null) {
                for (CrmTask _t : _theDayTasks) {
                    GetTaskForSpecialDayListItemResponse _tmpTask = new GetTaskForSpecialDayListItemResponse();
                    _tmpTask.setTaskbegintime(_simpleFormat.format(_t.getBegintime()));
                    _tmpTask.setTaskcontent(_t.getContent());
                    _tmpTask.setTaskid(_t.getRecid());
                    _theTasks.add(_tmpTask);
                }
            }
            _theDayTask.setTasks(_theTasks);
            _infos.add(_theDayTask);
        }

        return _infos;
    }

    @Transactional
    public ResultResponse addTaskMember(AddTaskMemberRequest _requesat, int userid) {
        int _result = 0;
        ResultResponse _resultResponse = new ResultResponse();

        String taskid = _requesat.getTaskid();
        List<Integer> _requestMembers = _requesat.getMembers();

        String _taskContent = "";
        List<CrmTask> _tasks = getTaskInfo(taskid);
        if (_tasks != null && _tasks.size() > 0) {
            _taskContent = _tasks.get(0).getContent();
        }

        String _taskContentShort = "";
        if (_taskContent.length() > 100) {
            _taskContentShort = _taskContent.substring(0, 100);
        } else {
            _taskContentShort = _taskContent;
        }

        List<String> _taskOnlyMember = new ArrayList<>();
        List<CrmTaskProjectRelation> _projectRelations = getTaskProjectRelation(taskid);
        if (_projectRelations != null && _projectRelations.size() > 0) {
            String _projectid = _projectRelations.get(0).getProjectid();
            int _stageid = _projectRelations.get(0).getStageid();

            if (!_projectid.isEmpty() && _stageid > 0) {
                List<CrmProjectMember> _members = _commonRepository.getProjectStagetMember(_projectid, _stageid, userid);
                for (Integer id : _requestMembers) {
                    long _theCount = _members.stream().filter(x -> x.getUserid() == id).count();
                    if (_theCount == 0) {
                        CrmUser _user = _commonRepository.getUserInfo(id);
                        _taskOnlyMember.add(_user.getRealname());
                    }
                }

                if (_taskOnlyMember.size() > 0) {
                    String _userNames = StringUtils.join(_taskOnlyMember.toArray(), ",");
                    String _projectName = "";
                    List<CrmProject> _projects = _commonRepository.getProject(_projectid);
                    if (_projects != null && _projects.size() > 0) {
                        _projectName = _projects.get(0).getRecname();
                    }

                    String _stageName = "";
                    List<CrmProjectStage> _projectStages = _commonRepository.getProjectStage(_stageid);
                    if (_projectStages != null && _projectStages.size() > 0) {
                        _stageName = _projectStages.get(0).getStagename();
                    }

                    String _errorMessage = String.format("请先将%s添加到%s项目的%s阶段!", _userNames, _projectName, _stageName);
                    _resultResponse.setMessage(_errorMessage);
                    _resultResponse.setResultcode(-1);
                    return _resultResponse;
                }
            }
        }

        //String groupid = "";
        List<TaskMember> _members = new ArrayList<>();
        for (Integer id : _requestMembers) {
            TaskMember _member = new TaskMember();
            _member.setIsmanager(false);
            _member.setIshost(false);
            _member.setUserid(id);
            _member.setOrder(0);
            _members.add(_member);
        }

        //check if task chat group exist
        int _taskChatType = BaseEnum.ChatType.Task.getChatType();
        boolean _isTaskChatGroupExist = false;
        String _lawyerGroupid = "";
        List<CrmChatGroupPart> _theTaskChatGroups = _commonRepository.getTaskChatGroup(taskid);
        if (_theTaskChatGroups != null && _theTaskChatGroups.size() > 0) {
            _lawyerGroupid = _theTaskChatGroups.get(0).getGroupid();
            _isTaskChatGroupExist = true;
        }

        //过滤已经存在的成员
        List<CrmTaskMember> _oldTaskMembers = getTaskMembers(taskid);
        List<TaskMember> _newTaskMembers = new ArrayList<>();
        for (TaskMember m : _members) {
            long _theCount = _oldTaskMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
            if (_theCount == 0) {
                _newTaskMembers.add(m);
            }
        }

        _result = insertTaskMember(taskid, _lawyerGroupid, _members, userid);
        if (_result > 0 && _isTaskChatGroupExist) {
            //把成员添加到im 聊天组
            _imService.addIMGroupMember(_lawyerGroupid, _requestMembers, userid);

        }

        /*
        //chat group and chat group member
        List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(taskid);
        if (_relations != null && _relations.size() > 0) {
            String _projectid = _relations.get(0).getProjectid();
            boolean _isNotExist = isInProjectMember(_projectid, taskid, userid);
            if (_isNotExist) {
                if (_isTaskChatGroupExist) {
                    //update chat status
                    //_commonRepository.updateChatGroupStatus(_lawyerGroupid, 1);

                    //把成员添加到im 聊天组
                    _imService.addIMGroupMember(_lawyerGroupid, _requestMembers, userid);

                } else {

                    int _addGroupResult = 0;
                    _lawyerGroupid = UUID.randomUUID().toString();
                    String _groupName = "律师协作团队";
                    String _imGroupName = "律师协作团队";
                    String _groupIntroduction = _taskContentShort;
                    int _lawyerGroupType = 0;
                    int _stageid = 0;
                    _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, taskid, _stageid, _taskChatType, _lawyerGroupType, userid);
                    if (_addGroupResult > 0) {
                        _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userid);
                        _imService.addIMGroupMember(_lawyerGroupid, _requestMembers, userid);
                    }
                }
            } else {
                if (!_lawyerGroupid.isEmpty()) {
                    //更新chat_group data recstatus=0
                    _commonRepository.updateChatGroupStatus(_lawyerGroupid, 0);
                }
            }
        } else {

            //如果没有关联任务，需要新建一个chat group
            if (_isTaskChatGroupExist) {
                _commonRepository.updateChatGroupStatus(_lawyerGroupid, 1);

                //把成员添加到im 聊天组
                _imService.addIMGroupMember(_lawyerGroupid, _requestMembers, userid);

            } else {

                int _addGroupResult = 0;
                _lawyerGroupid = UUID.randomUUID().toString();
                String _groupName = "律师协作团队";
                String _imGroupName = "律师协作团队";
                String _groupIntroduction = _taskContentShort;
                int _lawyerGroupType = 0;
                int _stageid = 0;
                _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, taskid, _stageid, _taskChatType, _lawyerGroupType, userid);
                if (_addGroupResult > 0) {
                    _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userid);

                    //把成员添加到im 聊天组
                    _imService.addIMGroupMember(_lawyerGroupid, _requestMembers, userid);
                }
            }
        }
*/
        /**
         * send system message
         */
        try {
            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            String _theMessage = "";
            String userIds = StringUtils.join(_members.stream().map(TaskMember::getUserid).toArray(), ",");
            ;
            String names = _commonRepository.getUserListByIds(userIds).stream().map(CrmUser::getRealname).collect(Collectors.joining(","));
            if (_projectRelations != null && _projectRelations.size() > 0) {
                _theMessage = String.format("%s修改了任务%s，添加了成员：%s", _theUser.getRealname(), _taskContent, names);
            } else {
                _theMessage = String.format("%s添加了成员：%s", _theUser.getRealname(), names);
            }
            List<String> _chatGroupIds = getChatGroupIds(taskid, userid);
            sendIMMessage(taskid, _chatGroupIds, _theMessage, userid, 0);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        _resultResponse.setResultcode(_result);
        _resultResponse.setMessage("");
        return _resultResponse;
    }

    //任务的成员是否全部属于项目的成员

    private boolean isInProjectMember(String projectid, String taskid, int userid) {

        //获取项目的成员
        List<CrmProjectMember> _projectMembers = _commonRepository.getProjectMember(projectid, userid);
        List<CrmTaskMember> _taskMembers = getTaskMembers(taskid);

        boolean _isNotExist = false;
        if (projectid.isEmpty()) {
            _isNotExist = true;
        } else {
            for (CrmTaskMember m : _taskMembers) {
                long _theMemberCount = _projectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                if (_theMemberCount == 0) {
                    _isNotExist = true;
                    break;
                }
            }
        }
        return _isNotExist;
    }

    @Transactional
    public int deleteTaskMember(DeleteTaskMemberRequest _requesat, int userid) {
        int _result = 0;

        String taskid = _requesat.getTaskid();
        int _deleteMemberId = _requesat.getMemberid();
        int _taskChatType = BaseEnum.ChatType.Task.getChatType();
        String _deleteMemberName = "";

        String _taskContent = "";
        List<CrmTask> _tasks = getTaskInfo(taskid);
        if (_tasks != null && _tasks.size() > 0) {
            _taskContent = _tasks.get(0).getContent();
        }


        String _taskContentShort = "";
        if (_taskContent.length() > 100) {
            _taskContentShort = _taskContent.substring(0, 100);
        } else {
            _taskContentShort = _taskContent;
        }

        List<Integer> _members = new ArrayList<>();
        _members.add(_deleteMemberId);

        //delete from database.
        List<CrmTaskMember> _savedMembers = getTaskMembers(taskid);
        if (_savedMembers != null) {
            for (CrmTaskMember m : _savedMembers) {
                if (m.getUserid() == _deleteMemberId) {
                    if (_deleteMemberName == "")
                        _deleteMemberName = m.getUsername();
                    else
                        _deleteMemberName = (_deleteMemberName + "," + m.getUsername());
                    if (m.ismanager() || m.ishost()) {
                        //can not delete manager, or host
                        _result = -1;
                        return _result;
                    } else {
                        _result = deleteTaskMember(m.getRecid(), userid);
                    }
                    break;
                }
            }
        }

        //current members of task
        List<Integer> _nowMembers = new ArrayList<>();
        for (CrmTaskMember m : _savedMembers) {
            if (m.getUserid() == _deleteMemberId) {
                continue;
            } else if (_nowMembers.contains(m.getUserid())) {
                continue;
            } else {
                _nowMembers.add(m.getUserid());
            }
        }

        //check if task chat group exist
        boolean _isTaskChatGroupExist = false;
        String _lawyerGroupid = "";
        List<CrmChatGroupPart> _theTaskChatGroups = _commonRepository.getTaskChatGroup(taskid);
        if (_theTaskChatGroups != null && _theTaskChatGroups.size() > 0) {
            _lawyerGroupid = _theTaskChatGroups.get(0).getGroupid();
            _isTaskChatGroupExist = true;
        }

        //从腾讯聊天组移除成员
        if (_isTaskChatGroupExist) {
            _imService.removeIMGroupMember(_lawyerGroupid, _members, userid);
        }

/*
        //chat group and chat group member
        List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(taskid);
        if (_relations != null && _relations.size() > 0) {
            String _projectid = _relations.get(0).getProjectid();
            boolean _isNotExist = isInProjectMember(_projectid, taskid, userid);
            if (_isNotExist) {
                if (_isTaskChatGroupExist) {

                    //update chat status
                    _commonRepository.updateChatGroupStatus(_lawyerGroupid, 1);
                    //remove member from im chat group
                    _imService.removeIMGroupMember(_lawyerGroupid, _members, userid);

                } else {

                    int _addGroupResult = 0;
                    _lawyerGroupid = UUID.randomUUID().toString();
                    String _groupName = "律师协作团队";
                    String _imGroupName = "律师协作团队";
                    String _groupIntroduction = _taskContentShort;
                    int _lawyerGroupType = 0;
                    int _stageid = 0;
                    _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, taskid, _stageid, _taskChatType, _lawyerGroupType, userid);
                    if (_addGroupResult > 0) {
                        _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userid);

                        //create task chat group,so add all member to the group
                        _imService.addIMGroupMember(_lawyerGroupid, _nowMembers, userid);
                    }
                }
            } else {
                if (_isTaskChatGroupExist) {

                    //remove member from im chat group
                    _imService.removeIMGroupMember(_lawyerGroupid, _members, userid);

                    //disable the existed task chat group
                    _commonRepository.updateChatGroupStatus(_lawyerGroupid, 0);
                }
            }
        } else {

            //如果没有关联任务，需要新建一个chat group
            if (_isTaskChatGroupExist) {
                _commonRepository.updateChatGroupStatus(_lawyerGroupid, 1);

                //remove member form task chat group
                _imService.removeIMGroupMember(_lawyerGroupid, _members, userid);

            } else {

                int _addGroupResult = 0;
                _lawyerGroupid = UUID.randomUUID().toString();
                String _groupName = "律师协作团队";
                String _imGroupName = "律师协作团队";
                String _groupIntroduction = _taskContentShort;
                int _lawyerGroupType = 0;
                int _stageid = 0;
                _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, taskid, _stageid, _taskChatType, _lawyerGroupType, userid);
                if (_addGroupResult > 0) {
                    _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userid);

                    //把成员添加到im 聊天组
                    _imService.addIMGroupMember(_lawyerGroupid, _nowMembers, userid);
                }
            }
        }

        */

        /**
         * send system message
         */

        try {
            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            List<CrmTaskProjectRelation> _projectRelations = getTaskProjectRelation(taskid);

            String _theMessage = "";
            String names = _deleteMemberName;
            if (_projectRelations != null && _projectRelations.size() > 0) {
                _theMessage = String.format("%s修改了任务%s，删除了成员：%s", _theUser.getRealname(), _taskContent, names);
            } else {
                _theMessage = String.format("%s删除了成员：%s", _theUser.getRealname(), names);
            }

            List<String> _chatGroupIds = getChatGroupIds(taskid, userid);
            sendIMMessage(taskid, _chatGroupIds, _theMessage, userid, 0);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return _result;
    }

    @Transactional
    public int setTaskManager(SetTaskManagerRequest _request, int userid) {

        String _taskid = _request.getTaskid();
        int _memberid = _request.getMemberid();
        String _memberName = "";

        List<CrmTaskMember> _members = getTaskMembers(_taskid);
        if (_members != null) {
            for (CrmTaskMember m : _members) {
                if (m.getUserid() == _memberid) {
                    _memberName = m.getUsername();
                    updateTaskMemberToManager(m.getRecid(), true);
                } else {
                    updateTaskMemberToManager(m.getRecid(), false);
                }
            }
        }

        /**
         * send system message
         */

        try {
            String _taskContent = "";
            List<CrmTask> _tasks = getTaskInfo(_taskid);
            if (_tasks != null && _tasks.size() > 0) {
                _taskContent = _tasks.get(0).getContent();
            }

            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            List<CrmTaskProjectRelation> _projectRelations = getTaskProjectRelation(_taskid);

            String _theMessage = "";
            if (_projectRelations != null && _projectRelations.size() > 0) {
                _theMessage = String.format("任务：%s的管理员变更为%s", _taskContent, _memberName);
            } else {
                _theMessage = String.format("本任务管理员变更为：%s", _memberName);
            }

            List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
            sendIMMessage(_taskid, _chatGroupIds, _theMessage, userid, 0);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return 1;
    }

    @Transactional
    public int setTaskHost(SetTaskManagerRequest _request, int userid) {

        String _taskid = _request.getTaskid();
        int _memberid = _request.getMemberid();
        String _memberName = "";

        List<CrmTaskMember> _members = getTaskMembers(_taskid);
        if (_members != null) {
            for (CrmTaskMember m : _members) {
                if (m.getUserid() == _memberid) {
                    _memberName = m.getUsername();
                    updateTaskMemberToHost(m.getRecid(), true);
                } else {
                    updateTaskMemberToHost(m.getRecid(), false);
                }
            }
        }

        /**
         * send system message
         */

        try {
            String _taskContent = "";
            List<CrmTask> _tasks = getTaskInfo(_taskid);
            if (_tasks != null && _tasks.size() > 0) {
                _taskContent = _tasks.get(0).getContent();
            }

            CrmUser _theUser = _commonRepository.getUserInfo(userid);
            List<CrmTaskProjectRelation> _projectRelations = getTaskProjectRelation(_taskid);
            String _theMessage = "";
            if (_projectRelations != null && _projectRelations.size() > 0) {
                _theMessage = String.format("任务：%s的主办人变更为%s", _taskContent, _memberName);
            } else {
                _theMessage = String.format("本任务主办人变更为：%s", _memberName);
            }

            List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
            sendIMMessage(_taskid, _chatGroupIds, _theMessage, userid, 0);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return 1;
    }

    private int updateTaskMemberToManager(String recid, boolean isManager) {

        int _result = 0;

        String _strSql = " update crm_task_member set ismanager=:ismanager where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _params.put("ismanager", isManager);
        _result = updateEntity(_strSql, _params);

        return _result;
    }

    private int updateTaskMemberToHost(String recid, boolean isHost) {

        int _result = 0;

        String _strSql = " update crm_task_member set ishost=:ishost where recid=:recid ";
        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", recid);
        _params.put("ishost", isHost);
        _result = updateEntity(_strSql, _params);

        return _result;
    }


    public void taskInfoChange() {


    }


    @Transactional
    public int deleteTaskFiles(TaskDeleteFileRequest _request, int userid) {

        int _result = deleteTaskFile(_request.getFilerecid(), userid);
        if (_result > 0) {

            /**
             * send system message
             */

            String _taskid = _request.getTaskid();

            try {
                String _taskContent = "";
                List<CrmTask> _tasks = getTaskInfo(_taskid);
                if (_tasks != null && _tasks.size() > 0) {
                    _taskContent = _tasks.get(0).getContent();
                }
                CrmUser _theUser = _commonRepository.getUserInfo(userid);
                List<CrmTaskFile> _taskFiles = getTaskFilesFilterStatus(_taskid, BaseEnum.Status.Disable.getStatus());
                String fileName = "";
                for (CrmTaskFile m : _taskFiles) {
                    if (m.getRecid().equals(_request.getFilerecid())) {
                        fileName = m.getFilename();
                        break;
                    }
                }

                String _theMessage = String.format("%s删除了文件：%s", _theUser.getRealname(), fileName);

                List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
                sendIMMessage(_taskid, _chatGroupIds, _theMessage, userid, 1);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return _result;
    }

    @Transactional
    public int renameTaskFile(TaskRenameFileRequest _request, int userid) {
        int _result = updateFileName(_request.getFilerecid(), _request.getNewfilename(), _request.getSourcefilename());
        if (_result > 0) {

            /**
             * send system message
             */

            String _taskid = _request.getTaskid();

            try {
                String _taskContent = "";
                List<CrmTask> _tasks = getTaskInfo(_taskid);
                if (_tasks != null && _tasks.size() > 0) {
                    _taskContent = _tasks.get(0).getContent();
                }
                CrmUser _theUser = _commonRepository.getUserInfo(userid);
                String _theMessage = String.format("%s重命名了文件：%s", _theUser.getRealname(), _request.getNewfilename());

                List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
                sendIMMessage(_taskid, _chatGroupIds, _theMessage, userid, 1);

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
        return _result;
    }

    public int updateFileName(String filerecid, String newFileName, String sourcefilename) {

        String _strSql = " update crm_task_file " +
                " set filename=:filename,sourcefilename=:sourcefilename " +
                " where recid=:recid ";

        Map<String, Object> _params = new HashMap<>();
        _params.put("recid", filerecid);
        _params.put("filename", newFileName);
        _params.put("sourcefilename", sourcefilename);
        return updateEntity(_strSql, _params);
    }

    @Transactional
    public int addTaskFile(TaskAddFileRequest _request, int userid) {

        int _result = 0;
        int _finalResult = 0;
        String _taskid = _request.getTaskid();
        List<TaskFileSimple> _files = _request.getFiles();
        for (TaskFileSimple _f : _files) {
            String uuid = UUID.randomUUID().toString();
            _result = insertTaskFile(uuid, _taskid, _f.getUploadfileid(), _f.getFilename(), _f.getSourcefilename(), userid);
            _finalResult += _result;

            /**
             * send system message
             */
            try {
                String _taskContent = "";
                List<CrmTask> _tasks = getTaskInfo(_taskid);
                if (_tasks != null && _tasks.size() > 0) {
                    _taskContent = _tasks.get(0).getContent();
                }
                CrmUser _theUser = _commonRepository.getUserInfo(userid);
                String _theMessage = String.format("%s上传了文件:%s", _theUser.getRealname(), _f.getFilename());

                List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
                String _fileName = _f.getFilename();
                String[] _parts = _fileName.split("\\.");
                String _fileExtention = "";
                if (_parts.length > 1) {
                    _fileExtention = _parts[1];

                }

                String _extraData = _f.getUploadfileid() + "." + _fileExtention;
                JSONObject extJsonObject = new JSONObject();
                extJsonObject.put("fileid", uuid);
                extJsonObject.put("uploadfileid", _f.getUploadfileid());
                extJsonObject.put("filename", _fileName);
                extJsonObject.put("ext", _fileExtention);

                sendIMMessageWithFile(_chatGroupIds, _theMessage, "file", _extraData, extJsonObject, userid);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return _finalResult;
    }
    @Transactional
    public int addTaskFile2(TaskAddFileRequest _request, int userid) {

        int _result = 0;
        int _finalResult = 0;
        String _taskid = _request.getTaskid();
        List<TaskFileSimple> _files = _request.getFiles();
        for (TaskFileSimple _f : _files) {
            String uuid = UUID.randomUUID().toString();
            _result = insertTaskFile(uuid, _taskid, _f.getUploadfileid(), _f.getFilename(), _f.getSourcefilename(), userid);
            _finalResult += _result;

            /**
             * send system message
             */
            try {
                String _taskContent = "";
                List<CrmTask> _tasks = getTaskInfo(_taskid);
                if (_tasks != null && _tasks.size() > 0) {
                    _taskContent = _tasks.get(0).getContent();
                }
                CrmUser _theUser = _commonRepository.getUserInfo(userid);
                String _theMessage = String.format("%s上传了文件:%s", _theUser.getRealname(), _f.getFilename());

                List<String> _chatGroupIds = getChatGroupIds(_taskid, userid);
                String _fileName = _f.getFilename();
                String[] _parts = _fileName.split("\\.");
                String _fileExtention = "";
                if (_parts.length > 1) {
                    _fileExtention = _parts[1];

                }

                String _extraData = _f.getUploadfileid() + "." + _fileExtention;
                JSONObject extJsonObject = new JSONObject();
                extJsonObject.put("fileid", uuid);
                extJsonObject.put("uploadfileid", _f.getUploadfileid());
                extJsonObject.put("filename", _fileName);
                extJsonObject.put("ext", _fileExtention);

                sendIMMessageWithFile2(_chatGroupIds, _theMessage, "file", _extraData, extJsonObject, userid);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return _finalResult;
    }


    public List<String> getChatGroupIds(String _taskid, int userid) {

        //get chat group id
        String _theTaskChatGroupId = "";
        String _theProjectClientChatGroupId = "";
        String _theProjectLawyerChatGroupId = "";
        List<String> _chatGroupIds = new ArrayList<>();

        List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(_taskid);
        if (_relations != null && _relations.size() > 0) {

            String _projectid = _relations.get(0).getProjectid();
            int _stageid = _relations.get(0).getStageid();

            List<CrmChatGroupPart> _projectChatGroup = _commonRepository.getProjectChatGroup(_projectid);
            List<CrmChatGroupPart> _projectStageChatGroup = _projectChatGroup.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
            Optional<CrmChatGroupPart> _projectClientChatGroup = _projectStageChatGroup.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();
            Optional<CrmChatGroupPart> _projectLawyerChatGroup = _projectStageChatGroup.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();
            if (_projectClientChatGroup.isPresent()) {
                _theProjectClientChatGroupId = _projectClientChatGroup.get().getGroupid();
            }
            if (_projectLawyerChatGroup.isPresent()) {
                _theProjectLawyerChatGroupId = _projectLawyerChatGroup.get().getGroupid();
            }

            List<CrmProjectMember> _theProjectMembers = _commonRepository.getProjectMember(_projectid, userid);
            List<CrmProjectMember> _theProjectClientMembers = _theProjectMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).collect(Collectors.toList());
            List<CrmProjectMember> _theProjectLawyerMembers = _theProjectMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()).collect(Collectors.toList());


            List<CrmProjectMember> _clientOnlyMembers = new ArrayList<>();
            for (CrmProjectMember m : _theProjectClientMembers) {
                long _theCount = _theProjectLawyerMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                if (_theCount == 0) {
                    _clientOnlyMembers.add(m);
                }
            }

            List<CrmTaskMember> _taskMembers = getTaskMembers(_taskid);
            for (CrmProjectMember m : _clientOnlyMembers) {
                long _theClientCount = _taskMembers.stream().filter(x -> x.getUserid() == m.getUserid()).count();
                if (_theClientCount > 0) {
                    _chatGroupIds.add(_theProjectClientChatGroupId);
                    break;
                }
            }
            _chatGroupIds.add(_theProjectLawyerChatGroupId);

        } else {
            List<CrmChatGroupPart> _taskChatGroup = _commonRepository.getTaskChatGroup(_taskid);
            if (_taskChatGroup != null && _taskChatGroup.size() > 0) {
                _theTaskChatGroupId = _taskChatGroup.get(0).getGroupid();
            }

            if (!_theTaskChatGroupId.isEmpty()) {
                _chatGroupIds.add(_theTaskChatGroupId);
            }
        }

        /*

        //if has task chat group, use the group
        List<CrmChatGroupPart> _taskChatGroup = _commonRepository.getChatGroup(_taskid, BaseEnum.ChatType.Task.getChatType());
        if (_taskChatGroup != null && _taskChatGroup.size() > 0) {
            _theTaskChatGroupId = _taskChatGroup.get(0).getGroupid();
        }

        if (!_theTaskChatGroupId.isEmpty()) {
            _chatGroupIds.add(_theTaskChatGroupId);
        } else {
            List<CrmTaskMember> _taskMembers = getTaskMembers(_taskid);
            if (_taskMembers != null && _taskMembers.size() > 0) {
                boolean _isInClientMember = false;
                boolean _isInLawyerMember = false;


                if (_relations != null && _relations.size() > 0) {

                    String _projectid = _relations.get(0).getProjectid();
                    int _stageid = _relations.get(0).getStageid();

                    List<CrmChatGroupPart> _projectChatGroup = _commonRepository.getChatGroup(_projectid, BaseEnum.ChatType.Project.getChatType());
                    List<CrmChatGroupPart> _projectStageChatGroup = _projectChatGroup.stream().filter(x -> x.getStageid() == _stageid).collect(Collectors.toList());
                    Optional<CrmChatGroupPart> _projectClientChatGroup = _projectStageChatGroup.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Client.getChatGroupType()).findFirst();
                    Optional<CrmChatGroupPart> _projectLawyerChatGroup = _projectStageChatGroup.stream().filter(x -> x.getGrouptype() == BaseEnum.ChatGroupType.Lawyer.getChatGroupType()).findFirst();
                    if (_projectClientChatGroup.isPresent()) {
                        _theProjectClientChatGroupId = _projectClientChatGroup.get().getGroupid();
                    }
                    if (_projectLawyerChatGroup.isPresent()) {
                        _theProjectLawyerChatGroupId = _projectLawyerChatGroup.get().getGroupid();
                    }

                    //if task member in project client member, lawyer member
                    List<CrmProjectMember> _theProjectMembers = _commonRepository.getProjectMember(_projectid, userid);
                    for (CrmTaskMember m : _taskMembers) {
                        List<CrmProjectMember> _tempMembers = _theProjectMembers.stream().filter(x -> x.getUserid() == m.getUserid()).collect(Collectors.toList());
                        long _theClientCount = _tempMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Client.getGroupType()).count();
                        if (_theClientCount == 0) {
                            _isInClientMember = false;
                        } else {
                            long _theLawyerCount = _tempMembers.stream().filter(x -> x.getGrouptype() == BaseEnum.GroupType.Lawyer.getGroupType()).count();
                            if (_theLawyerCount == 0) {
                                _isInLawyerMember = false;
                            }
                        }
                    }
                    if (_isInClientMember) {
                        _chatGroupIds.add(_theProjectClientChatGroupId);
                    }
                    if (_isInLawyerMember) {
                        _chatGroupIds.add(_theProjectLawyerChatGroupId);
                    }
                }
            }
        }

        */
        return _chatGroupIds;
    }

    @Transactional
    public int updateTaskBeginTime(SaveTaskBeginTimeRequest _request, int userid) throws Exception {
        int _result = 0;

        String _taskid = _request.getRecid();
        String _beginTime = _request.getBegintime();

        SimpleDateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String _strSql = " update crm_task set begintime=:begintime where recid=:recid";
        Map<String, Object> _param = new HashMap<>();
        _param.put("begintime", _dateFormat.parse(_beginTime));
        _param.put("recid", _taskid);

        _result = updateEntity(_strSql, _param);
        return _result;

    }

    public int setTaskChatGroupActive(String groupid, boolean isactive) throws Exception {
        int _result = 0;
        String _strSql = " update crm_chat_group set isactive=:isactive " +
                " where recid=:recid ";
        Map<String, Object> _param = new HashMap<>();
        _param.put("recid", groupid);
        _param.put("isactive", isactive);
        _result = updateEntity(_strSql, _param);
        return _result;
    }

    public CrmChatGroup getTaskChatGroup(String taskid) {
        String _strSql = "select color,recid,recname,objectid,chattype,chatstageid,prefixname,stageid,grouptype,relatedid,''as taskbegintime,isactive,createtime " +
                " from crm_chat_group " +
                " where objectid=:objectid ";
        Map<String, Object> _param = new HashMap<>();
        _param.put("objectid", taskid);

        List<CrmChatGroup> _list = getEntitys(_strSql, _param, CrmChatGroup.class);
        if (_list != null && _list.size() > 0) {
            return _list.get(0);
        } else {
            return null;
        }
    }


    public List<TaskFile> getTaskFiles(GetTaskFileRequest _request, int userid) {
        String _taskid = _request.getTaskid();
        List<CrmTaskFile> _files = getTaskFiles(_taskid, userid);
        List<TaskFile> _filesResponse = new ArrayList<>();
        for (CrmTaskFile _f : _files) {
            _filesResponse.add(toTaskFile(_f));
        }

        return _filesResponse;

    }


    public List<CrmTask> getCrmTaskPage(GetTaskPageItemsRequest _request, int userid) {
        int _pageIndex = _request.getPageindex();
        int _pageSize = _request.getPagesize();
        String _searchKey = _request.getSearchkey();
        int _offset = _pageSize * (_pageIndex - 1);

        String _strSql = " select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime" +
                " from crm_task " +
                " where recstatus=1 " +
                " and  recid in (select taskid   from crm_task_member where recstatus=1 and userid=:userid)" +
                " and  content like  '%" + _searchKey + "%'" +
                " order by createtime desc limit " + _pageSize + " offset " + _offset;


        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        List<CrmTask> _tasks = getEntitys(_strSql, _params, CrmTask.class);
        return _tasks;
    }


    public PageSummary getTaskPageCount(GetTaskPageItemsRequest _request, int userid) {
        int _pageIndex = _request.getPageindex();
        int _pageSize = _request.getPagesize();
        String _searchKey = _request.getSearchkey();

        int _pageCount = 0;
        int _total = 0;
        String _strCountSql = " select count(1) " +
                " from crm_task " +
                " where recstatus=1 " +
                " and  recid in (select taskid   from crm_task_member where recstatus=1 and userid=:userid)" +
                " and  content like  '%" + _searchKey + "%'";

        Map<String, Object> _params = new HashMap<>();
        _params.put("userid", userid);
        _total = getEntityCount(_strCountSql, _params);

        if ((_total % _pageSize) > 0) {
            _pageCount = (_total / _pageSize) + 1;
        } else {
            _pageCount = _total / _pageSize;
        }

        PageSummary _pageSummary = new PageSummary();
        _pageSummary.setPage(_pageCount);
        _pageSummary.setTotal(_total);

        return _pageSummary;
    }


    public List<TaskInfo> getTaskinfoPage(List<CrmTask> tasks, int userid) {
        List<TaskInfo> _aheadTypeResponse = new ArrayList<>();
        try {
            if (tasks != null && tasks.size() > 0) {
                for (CrmTask _t : tasks) {

                    String _taskid = _t.getRecid();
                    TaskInfo _info = toTaskInfo(_t);

                    //set project name and stage name
                    List<CrmTaskProjectRelation> _relations = getTaskProjectRelation(_taskid);
                    if (_relations != null && _relations.size() > 0) {

                        String _projectName = "";
                        String _stageName = "";
                        int _projectType = 0;

                        CrmTaskProjectRelation _relation = _relations.stream().findFirst().get();
                        String _projectid = _relation.getProjectid();
                        if (_projectid != null && !_projectid.isEmpty()) {
                            List<CrmProject> _projectList = _commonRepository.getProject(_projectid);
                            if (_projectList != null && _projectList.size() > 0) {
                                CrmProject _project = _projectList.get(0);
                                _projectName = _project.getRecname();
                                _projectType = _project.getProjecttype();

                                List<CrmProjectStage> _stageList = _commonRepository.getProjectStageList(_projectid);
                                if (_stageList != null && _stageList.size() > 0) {
                                    CrmProjectStage _stageInfo = _stageList.get(0);
                                    _stageName = _stageInfo.getStagename();
                                }
                            }
                        }
                        _info.setProjectname(_projectName);
                        _info.setProjectid(_relation.getProjectid());
                        _info.setProjecttype(_projectType);
                        _info.setStagename(_stageName);
                        _info.setStageid(_relation.getStageid());

                    } else {
                        _info.setProjectname("");
                        _info.setStagename("");
                    }

                    List<CrmTaskMember> _members = getTaskMembers(_taskid);
                    List<CrmTaskMember> _tmpMembers1 = _members.stream().filter(x -> x.getUserid() == userid && x.ishost()).collect(Collectors.toList());
                    boolean _isHost = false;
                    if (_tmpMembers1 != null && _tmpMembers1.size() > 0) {
                        _isHost = true;
                    }

                    boolean _isManager = false;
                    List<CrmTaskMember> _tmpMembers2 = _members.stream().filter(x -> x.getUserid() == userid && x.ismanager()).collect(Collectors.toList());
                    if (_tmpMembers2 != null && _tmpMembers2.size() > 0) {
                        _isManager = true;
                    }
                    _info.setIshost(_isHost);
                    _info.setIsmanager(_isManager);

                    CrmChatGroup _chatGroup = _commonRepository.getChatGroup(_taskid);
                    if (_chatGroup != null) {
                        String _groupid = _chatGroup.getGroupid();
                        _info.setChatgroupid(_groupid);
                    } else {
                        _info.setChatgroupid("");
                    }
                    _aheadTypeResponse.add(_info);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
        return _aheadTypeResponse;
    }


    //获取未完成的task
    public List<CrmTask> getUnCompletedTasks(String searchKey, int userid) {

        String _strSql = " select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime" +
                " from crm_task " +
                " where recstatus=1 " +
                " and taskstatus!=2 " +
                " and  recid in (select taskid from crm_task_member where recstatus=1 and userid=:userid)" +
                " and recid not in ( select taskid from crm_project_task where recstatus=1 and taskid is not null and projectid is not null and stageid>0 ) " +
                " and  content like  '%" + searchKey + "%'" +
                " order by taskstatus asc ,begintime asc";
        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTask.class);
        _query.setParameter("userid", userid);
        return _query.getResultList();

    }


    public int createTaskChatGroup(String _taskid, String _taskContent, int _stageid, int _chatType, String _lawyerGroupid, List<TaskMember> _taskMembers, int userid,String color) {

        //add im group
        //律师协作团队
        int _addGroupResult = 0;

        //String _groupName = _taskName + "律师协作团队";
        String _groupName = "律师协作团队";
        String _imGroupName = "律师协作团队";

        String _taskContentShort = "";
        if (_taskContent.length() > 100) {
            _taskContentShort = _taskContent.substring(0, 100);
        } else {
            _taskContentShort = _taskContent;
        }

        if (_taskContent.length() > 10) {
            _groupName = _taskContent.substring(0, 10);
        } else {
            _groupName = _taskContent;
        }


        String _groupIntroduction = _taskContentShort;

        int _lawyerGroupType = 0;
        _addGroupResult = insertChatGroup(_lawyerGroupid, _groupName, _taskid, _stageid, _chatType, _lawyerGroupType, userid,color);
        boolean _createIMGroupResult = false;
        if (_addGroupResult > 0) {
            _createIMGroupResult = _imService.createIMGroup(_lawyerGroupid, _imGroupName, _groupIntroduction, userid);
        }

        insertTaskMember(_taskid, _lawyerGroupid, _taskMembers, userid);

        boolean _addMemberToIM = false;
        if (_createIMGroupResult) {
            List<Integer> _members = new ArrayList<>();
            for (TaskMember member : _taskMembers) {
                _members.add(member.getUserid());
            }

            //添加member到im group
            _addMemberToIM = _imService.addIMGroupMember(_lawyerGroupid, _members, userid);
        }

        if (_addMemberToIM) {
            return 1;
        } else {
            return 0;
        }


    }

    public List<CrmTask> getTasksOnTime() {
        String _strSql = " select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime" +
                " from crm_task " +
                " where recstatus=1 " +
//                " and TIMESTAMPDIFF(MINUTE, CONVERT_TZ(begintime,'+00:00','+8:00'), now())=0  " +
                " and TIMESTAMPDIFF(MINUTE, begintime, now())=0  " +
                " and taskstatus!=2 " +
                " order by createtime desc ";

        return getEntitys(_strSql, null, CrmTask.class);

    }

    public List<CrmTask> getTasksOnTime(String time) {
        String _strSql = " select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime" +
                " from crm_task " +
                " where recstatus=1 " +
//                " and TIMESTAMPDIFF(MINUTE, CONVERT_TZ(begintime,'+00:00','+8:00'), now())=0  " +
                " and TIMESTAMPDIFF(MINUTE, begintime, :time ) = 0  " +
                " and taskstatus!=2 " +
                " order by createtime desc ";


        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTask.class);
        _query.setParameter("time", time);
        List<CrmTask> tasks = _query.getResultList();
        return tasks;

//        return getEntitys(_strSql, param, CrmTask.class);

    }

    public List<CrmTask> getTasks24Hours() {

        //1440
        //todo: fix time zone issuea
        String _strSql = " select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime" +
                " from crm_task " +
                " where recstatus=1 " +
//                " and TIMESTAMPDIFF(MINUTE, CONVERT_TZ(begintime,'+00:00','+8:00'), now())=1440  " +
                " and TIMESTAMPDIFF(MINUTE, begintime, now())=1440  " +
                " and taskstatus!=2 " +
                " order by createtime desc ";

        return getEntitys(_strSql, null, CrmTask.class);

    }

    public List<CrmTask> getTaskListMainPage(TaskListRequest _request, int userid) {
        String searchKey = _request.getSearchkey();
        String _strSql = "  select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime " +
                " from crm_task " +
                " where recstatus=1  " +
                " and  recid in (select taskid   from crm_task_member where recstatus=1 and userid=:userid)" +
                " and  content like  '%" + searchKey + "%'";

//        _strSql += "  order by taskstatus asc ,begintime asc ";
        //  2022/6/27  排序修改
        _strSql += " ORDER BY FIELD( taskstatus, 1, 2, 0 ), CASE taskstatus WHEN 1 THEN begintime END ASC, CASE taskstatus WHEN 2 THEN completetime END DESC ";
        if (_request.getPageindex() > 0) {
            int _pageindex = _request.getPageindex();
            int _pageSize = _request.getPagesize();
            int _offset = (_pageindex - 1) * _pageSize;
            _strSql += "  limit " + _pageSize + " offset " + _offset;
        }

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTask.class);
        _query.setParameter("userid", userid);
        List<CrmTask> tasks = _query.getResultList();
        return tasks;

    }


    public List<CrmTask> getTaskListMain(String searchKey, int userid) {

        String _strSql = "  select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime " +
                " from crm_task " +
                " where recstatus=1  " +
                " and taskstatus!=2 " +
                " and  recid in (select taskid   from crm_task_member where recstatus=1 and userid=:userid)" +
                " and  content like  '%" + searchKey + "%'";


        _strSql += " union all  ";

        _strSql += "  select recid, coalesce(recname,'') as recname,begintime,content,contenttype,address_name,address_location,taskstatus,completetime " +
                " from crm_task " +
                " where recstatus=1  " +
                " and taskstatus=2 " +
                " and  recid in (select taskid   from crm_task_member where recstatus=1 and userid=:userid)" +
                " and  content like  '%" + searchKey + "%'";


        _strSql += "  order by taskstatus asc ,begintime asc ";
        // _strSql += "  order by completetime desc ";


        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmTask.class);
        _query.setParameter("userid", userid);
        return _query.getResultList();
    }

    private List<String> getPhoneByIds(List<Integer> userIdList) {
        String strSql = " SELECT username FROM crm_user WHERE recstatus = 1 and id IN ( :userids )";
        javax.persistence.Query query = getEntityManager().createNativeQuery(strSql);
        query.setParameter("userids", userIdList);
        return query.getResultList();
    }

    public int setFileViewed(TaskViewdFileRequest _requset, int userid) {

        String _fileid = _requset.getFileid();
        String _strSql = " update crm_task_file set isviewed=true where recid=:recid ";

        int _theCount = _commonRepository.getFileViewedCount(_fileid, userid);
        if (_theCount == 0) {

            _strSql = " insert into crm_view_file_history(recid,filerecid,viewerid,reccreator)values(:recid,:filerecid,:viewerid,:reccreator)";
            Map<String, Object> _params = new HashMap<>();

            String _recId = UUID.randomUUID().toString();
            _params.put("recid", _recId);
            _params.put("filerecid", _fileid);
            _params.put("viewerid", userid);
            _params.put("reccreator", userid);

            return updateEntity(_strSql, _params);
        } else {
            return 1;
        }
    }

    public List<CrmChatGroup> getMyFinishedTaskGroup(int userid) {
        String _strSql = " select color,recid,recname,objectid,chattype,chatstageid,prefixname,stageid,grouptype,relatedid,'' as taskbegintime,isactive,createtime from crm_chat_group " +
                " where objectid in(select recid " +
                " from crm_task " +
                " where recstatus=1  " +
                " and taskstatus=2 " +
                " and reccreator=:userid " +
                " ) ";
        _strSql += "  order by createtime ";

        javax.persistence.Query _query = getEntityManager().createNativeQuery(_strSql, CrmChatGroup.class);
        _query.setParameter("userid", userid);
        return _query.getResultList();
    }

    public String getSmsMessage(TaskMember memer, String taskContent, String taskBegintime) {
        String title = "参与";
        if (memer.getIshost() == true)
            title = "主办";
        String _smsMessage = String.format("您有%s的任务[%s]将于%s开始，请打开法力app查看。", title, taskContent, taskBegintime);

        return _smsMessage;
    }

    //end of class

}
